Xor encryption in PHP Xor encryption in PHP php php

Xor encryption in PHP


How i did it, might help someone ...

$msg = 'say hi!';$key = 'whatever_123';// print, and make unprintable chars available for a link or alike.// using $_GET, php will urldecode it, if it was passed urlencodedprint "obfuscated, ready for url: " . urlencode(obfuscate($msg, $key)) . "\n";print "deObfuscated: " . obfuscate(obfuscate($msg, $key), $key);function obfuscate($msg, $key) {    if (empty($key)) return $msg;    return $msg ^ str_pad('', strlen($msg), $key);}


I think you might have a few problems here, I've tried to outline how I think you can fix it:

  • You need to use ord(..) to get the ASCII value of a character so that you can represent it in binary. For example, try the following:

    printf("%08b ", ord('A')); // outputs "01000001"
  • I'm not sure how you do an XOR cipher with a multi-byte key, as the wikipedia page on XOR cipher doesn't specify. But I assume for a given key like "123", your key starts "left-aligned" and extends to the length of the text, like this:

    function xor_this($text) {    $key = '123';    $i = 0;    $encrypted = '';    foreach (str_split($text) as $char) {        $encrypted .= chr(ord($char) ^ ord($key{$i++ % strlen($key)}));    }    return $encrypted;}print xor_this('hello'); // outputs "YW_]]"

    Which encrypts 'hello' width the key '12312'.


There's no guarantee that the result of the XOR operation will produce a printable character. If you give us a better idea of the reason you're doing this, we can probably point you to something sensible to do instead.