Trying to "encrypt" a JavaScript string with PHP and then decode it using JavaScript.
The PHP function for encryption:
function xor_string( $text, $xorKey ) {
$xored = '';
$chars = str_split( $text );
$i = 0;
while ( $i < count( $chars ) ) {
$xored .= chr( ord( $chars[$i] ) ^ $xorKey );
$i++;
}
return $xored;
}
The JavaScript decryption function:
function xor_string( str, key ) {
var xored = "";
for (i=0; i<str.length;i++) {
var a = str.charCodeAt(i);
var b = a ^ key;
xored = xored+String.fromCharCode(b);
}
console.log(xored);
}
This method works with certain keys but fails with others. For example:
echo urlencode( xor_string( 'document.location.href.search', 67 ) );
Returns:
%27%2C+6.%26-7m%2F%2C+%227%2A%2C-m%2B1%26%25m0%26%221+%2B
When attempting to "decode" it with JavaScript using:
var str = decodeURIComponent("%27%2C+6.%26-7m%2F%2C+%227%2A%2C-m%2B1%26%25m0%26%221+%2B");
xor_string( str, 67 );
The result is:
dohument.lohation.href.searhh
Unsure why this inconsistency is occurring. Has anyone encountered this issue before?
Works well with some "keys" like 120, but encounters failures with many others.