目前在公司重构专案,由php翻成nodejs,遇到编码会不一致问题,不知如何解决,有请大大帮小弟解答,以下附上nodejs与php代码.
<?php
$h = hex2bin('c8a35122a3dbae742a1da6b1868fdbca');
$h = hash("sha256", $h);
echo $h;
import SHA256 from 'crypto-js/sha256'
(async() => {
function hex2bin (s) {
// discuss at: http://locutus.io/php/hex2bin/
// original by: Dumitru Uzun (http://duzun.me)
// example 1: hex2bin('44696d61')
// returns 1: 'Dima'
// example 2: hex2bin('00')
// returns 2: '\x00'
// example 3: hex2bin('2f1q')
// returns 3: false
var ret = []
var i = 0
var l
s += ''
for (l = s.length; i < l; i += 2) {
var c = parseInt(s.substr(i, 1), 16)
var k = parseInt(s.substr(i + 1, 1), 16)
if (isNaN(c) || isNaN(k)) return false
ret.push((c << 4) | k)
}
return String.fromCharCode.apply(String, ret)
}
var h = await hex2bin('c8a35122a3dbae742a1da6b1868fdbca')
h = await SHA256(h).toString()
console.log(h)
})()
$ php test.php
812d2ab805b8144bc5ba87c62abcbcff57eac23a7b5b113487560eb3fa3d25c7
$ babel-node test.js
e6b036bfd0fe9394d81ecd55c586d72a18d7d32f217f6770d071ff1484455dfd