我尝试在PHP和JS中对两个字符串进行异或运算,结果不同:
PHP函数
function xh($a, $b) {
$res = ""; $i = strlen($a); $j = strlen($b);
while($i-->0 && $j-->0) {
$res.= $a[$i] ^ $b[$j];
}
return base64_encode($res);
}
JS函数
function xh(a, b) {
var res = "", i = a.length, j = b.length;
while (i-->0 && j-->0) {
res+= String.fromCharCode(a.charCodeAt(i) ^ b.charCodeAt(j));
}
return btoa(res);
}
我检查了字节,并发现PHP函数中的第六个字节始终为零,因此我更新了JS函数以生成相同的结果。 对应于PHP函数的JS函数
function xh2(a, b) {
var res = "", i = a.length, j = b.length;
while (i-->0 && j-->0) {
res+= String.fromCharCode((a.charCodeAt(i) ^ b.charCodeAt(j)) & 95);
}
return btoa(res);
}
那个位是发生了什么?
示例输入/输出:
string a: 5D41402ABC4B2A76B9719D911017C592
string b: FE2D010308A6B3799A3D9C728EE74244
PHP says: Bg0HVwBUVQkDDgcAVQRYWw8AUlBUVVtSUgIBBFUGAVM=
JS says: Bg0HdwB0dQkDDgcAdQR4ew8AcnB0dXtycgIBBHUGAXM=
JS2 says: Bg0HVwBUVQkDDgcAVQRYWw8AUlBUVVtSUgIBBFUGAVM=
在这个例子中的第一个区别:
C: 0x43 = 0100 0011
4: 0x34 = 0011 0100
C^4 (JS) = 0111 0111 = 0x77 (correct)
C^4 (PHP)= 0101 0111 = 0x57
^
sixth bit wrong
输入是MD5哈希值,使用默认编码,我的OEM字符集为CP1250,语言环境为cs-cz,文件以UTF-8编码存储,如果以下任何一项有影响,则页面通过HTTP头text/html;charset=UTF-8和meta标签UTF-8生成。
我的Web服务器是Mongoose 6.7,带有捆绑的php 5.6(cgi)。我还尝试了最新的7.3版(x86和x64),但结果相同,但是评论中的@apokryfos在测试中第六位是正确的。
(i--)>0
- Jan Turoň(i--)> 0
。 - LF00