5

I need to XOR a string/text in PHP the base64 encode it, but something goes wrong:

<?php

$mustget = 'Kw4SCQ==';
$string = 'Josh';

echo("Must get: " . $mustget . "\n");
echo("We got: " . base64_encode(xor_this($string)) . "\n");

function xor_this($text) {
    $key = 'frtkj';
    $i = 0;
    $encrypted = '';
    foreach (str_split($text) as $char) {
        $encrypted .= chr(ord($char) ^ ord($key{$i++ % strlen($key)}));
    }
    return $encrypted;
}

?>

I get the following result, but I need to get the "$mustget" one:

Must get: Kw4SCQ==
We got: LB0HAw==

What do I do wrong?

8
  • I'm working on decrypting a malware in the wild that uses that "encryption" to communicate with its PHP admin panel: blog.spiderlabs.com/2012/12/…
    – bsteo
    Dec 14, 2012 at 9:35
  • Question is, how did you get that result $mustget = 'Kw4SCQ==' ?
    – Touki
    Dec 14, 2012 at 9:36
  • @xtmtrx: "Each character in the decoded string is xored sequentially against each character of the key we previously identified". So you should xor each data character with each key character
    – zerkms
    Dec 14, 2012 at 9:36
  • 1.The data is Base64 decoded 2.Each character in the decoded string is xored sequentially against each character of the key we previously identified. In Ruby, it looks something like this: "A".xor("f").xor("r").xor("t").xor("k").xor("j")
    – bsteo
    Dec 14, 2012 at 9:37
  • @xtmtrx: right "A".xor("f").xor("r").xor("t").xor("k").xor("j") --- you xor data character with every key character, not with one
    – zerkms
    Dec 14, 2012 at 9:37

1 Answer 1

9
$mustget = 'Kw4SCQ==';

$key = 'frtkj';
$key_length = strlen($key);

$encoded_data = base64_decode($mustget);

$result = '';

$length = strlen($encoded_data);
for ($i = 0; $i < $length; $i++) {
    $tmp = $encoded_data[$i];

    for ($j = 0; $j < $key_length; $j++) {
        $tmp = chr(ord($tmp) ^ ord($key[$j]));
    }

    $result .= $tmp;
}

echo $result; // Josh

http://ideone.com/NSIe7K

I'm sure you can reverse it and create a function, that "crypts" the data ;-)

1
  • Modulo is your friend !
    – Drasill
    Dec 30, 2013 at 15:17

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.