Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Implement PHP string xor with JavaScript

I would like to convert this PHP code$a ^ $b(where length of a is 16, b is 32) to javascript code. Here is my implementation.

    var xor = "";
    for (var i = 0; i < a.length; i++) {
        xor += String.fromCharCode(a.charCodeAt(i) ^ b.charCodeAt(i));
    }
    xor = b.substr(-16) + xor;

However, the result not the same. Please help me to figure it out. Thanks.

By the way, here's the part of code I'm working around:

    var secret = "secret";
    var password = "password";
    var chal = "2ba5565a539c57c1ce2356e218faa321";
    var hexchal = php.pack('H32', chal);
    var newchal, newpwd, pappassword;

    newchal = php.pack('H*', php.md5(hexchal + secret));
    newpwd = php.pack("a32", password);
    var xor = "";
    for (var i = 0; i < newchal.length; i++) {
        xor += String.fromCharCode(newchal.charCodeAt(i) ^ newpwd.charCodeAt(i));
    }
    xor = newpwd.substr(-16) + xor;

The corresponding PHP code:

    <?php
    $secret = "secret";
    $password = "password";
    $chal = "2ba5565a539c57c1ce2356e218faa321";

    $hexchal = pack ("H32", $chal);
    $newchal = pack ("H*", md5($hexchal . $secret));

    $newpwd = pack("a32", $password);
    $pappassword = implode ("", unpack("H32", ($newpwd ^ $newchal)));
    echo $pappassword;
    ?>

Where a and b are newchal and newpwd, respectively. And php.func()s come from http://phpjs.org/. The expected output is "821f984aa1062e56dbdc8f77454e5eb3".

like image 911
Trantor Liu Avatar asked Jun 06 '12 05:06

Trantor Liu


2 Answers

I've used your code almost literally:

String.prototype.xor = function(other)
{
  var xor = "";
  for (var i = 0; i < this.length && i < other.length; ++i) {
      xor += String.fromCharCode(this.charCodeAt(i) ^ other.charCodeAt(i));
  }
  return xor;
}

The loop should stop when the end of either string is reached.

Tested with:

String.prototype.toHex = function() {
    var hex = '', tmp;
    for(var i=0; i<this.length; i++) {
        tmp = this.charCodeAt(i).toString(16)
        if (tmp.length == 1) {
            tmp = '0' + tmp;
        }
        hex += tmp
    }
    return hex;
}

var x = "password\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000";
var y = "\u00f2~\u00eb9\u00d6i\\2\u00db\u00dc\u008fwEN^\u00b3";

x.xor(y).toHex();

Output:

821f984aa162e56dbdc8f77454e5eb3
like image 143
Ja͢ck Avatar answered Nov 05 '22 14:11

Ja͢ck


You forgot to add a check if the length of b exceeds:

if(i < b.length){
    xor += String.fromCharCode(a.charCodeAt(i) ^ b.charCodeAt(i));
}else{
    xor += a.charAt(i);
}
like image 1
Corsair Avatar answered Nov 05 '22 12:11

Corsair