我想将这个
PHP代码$a ^ $b(其中a的长度为16,b为32)转换为javascript代码.这是我的实施.
var xor = ""; for (var i = 0; i < a.length; i++) { xor += String.fromCharCode(a.charCodeAt(i) ^ b.charCodeAt(i)); } xor = b.substr(-16) + xor;
但是,结果不一样.请帮我解决一下.谢谢.
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;
<?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; ?>
其中a和b分别是newchal和newpwd. PHP.func()来自http://phpjs.org/.预期输出为“821f984aa1062e56dbdc8f77454e5eb3”.
解决方法
我几乎用字面意思地使用了你的代码:
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; }
当到达任一字符串的末尾时,循环应该停止.
经测试:
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();
输出:
821f984aa162e56dbdc8f77454e5eb3