// base64-encode the binary result of the HMAC computation
$merchantSig = base64_encode(hash_hmac('sha256',$signData,pack("H*" , $hmacKey),true));
以上是生成摘要的php代码。
let h = crypto.createHmac('sha256', hmacKey).update(keyString).digest('base64');
以上是生成摘要的nodejs代码。我使用的 key 在 php 和 node 中都是十六进制的。我应该在 node 中做些什么来获得与 php 中相同的结果?我知道 php 使用与 nodejs 不同的编码。但是,我还缺少什么?
最佳答案
好吧,php 和 node.js 中的 hmac 没有区别。
这是您提供的两段代码的正常行为。
在你的 php 中你正在打包
你的 $hmacKey
您 Node 端不存在的步骤;
在接下来的所有示例中,我将使用 123456
作为 hmac key ,使用 yello
作为数据字符串
例如:
php 没有打包:
$merchantSig = base64_encode(hash_hmac('sha256',$signData, $hmacKey,true));
echo $merchantSig; // output : gKjrFq1nrRP33vGiAK9V1Z5bLX5EFZhcfy2flRIGPEI=
node.js 没有打包:
let h = crypto.createHmac('sha256', hmacKey).update(keyString).digest('base64');
console.log(h); // output : gKjrFq1nrRP33vGiAK9V1Z5bLX5EFZhcfy2flRIGPEI=
现在让我们打包两者:
php 打包:
$merchantSig = base64_encode(hash_hmac('sha256',$signData,pack("H*" , $hmacKey),true));
echo $merchantSig; // output : Y8D5crzxQfFkwQn1OJHeZTS1KVuTH0y7qLuxyetE0TY=
node.js 打包 here is the trick
var h = crypto.createHmac('sha256', hmacKey.packHex()).update(keyString).digest('base64');
// ^^^^^^^^^
console.log(h); // output : Y8D5crzxQfFkwQn1OJHeZTS1KVuTH0y7qLuxyetE0TY=
更新
下面是两种情况下php和nodejs的一些在线测试(使用pack-不使用pack)
nodejs : http://rextester.com/YNNWN69327
这是另一个使用另一个键和字符串进行的测试。对于 PHP:
和 node.js
关于php - nodejs和php生成的不同HMAC,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43063221/