由nodejs和php生成的不同HMAC [英] Different HMACs generated by nodejs and php

查看:195
本文介绍了由nodejs和php生成的不同HMAC的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

// base64-encode the binary result of the HMAC computation
$merchantSig = base64_encode(hash_hmac('sha256',$signData,pack("H*" , $hmacKey),true));

上面是生成摘要的php代码。

The above is the php code that generates the digest.

let h = crypto.createHmac('sha256', hmacKey).update(keyString).digest('base64');

上面是生成摘要的nodejs代码。我使用的密钥在php和node中都是十六进制的。为了在php中获得相同的结果,我应该在node上做些什么。我知道php使用的编码与nodejs不同。但是,我在这里还缺少什么?

The above is the nodejs code that generates the digest. The key that I am using is hexadecimal in both php and node. What should I be doing differently in node to get the same result as that in php. I know php uses a different encoding than nodejs. But, what else am I missing here?

推荐答案

好吧,php和node.js中的hmac之间没有区别

well, there are no difference between the hmac's in both php and node.js .

这是您提供的两段代码的正常行为。

this is the normal behavior for the two pieces of codes your provided.

在您的php中打包您的 $ hmacKey

不是存在于您的节点端;

the step which is not exists in your node side;

在接下来的所有示例中,我将使用 123456 作为hmac密钥, yello 作为数据字符串

in all the next examples i will use 123456 as hmac key and yello as a data string

例如:

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=






现在打包两者:


now let's pack the both :

php 带包装:

$merchantSig = base64_encode(hash_hmac('sha256',$signData,pack("H*" , $hmacKey),true));
echo $merchantSig; // output : Y8D5crzxQfFkwQn1OJHeZTS1KVuTH0y7qLuxyetE0TY=

node.js ,带有包装 这就是窍门

var h = crypto.createHmac('sha256', hmacKey.packHex()).update(keyString).digest('base64');
//                                          ^^^^^^^^^
console.log(h); // output : Y8D5crzxQfFkwQn1OJHeZTS1KVuTH0y7qLuxyetE0TY=






Update



以下是一些针对php&两种情况下的nodejs(使用pack-不使用pack)


Update

Here is some online tests for both php & nodejs in the two cases (using pack-without using pack)

php: https://3v4l.org/HCt4g

nodejs: http://rextester.com/YNNWN69327

这是另一个使用其他键和字符串的测试。对于php:

here is another tests with another keys and strings . for php :

https://3v4l.org/JKdNk

和node.js

http://rextester.com/RXGM49887

这篇关于由nodejs和php生成的不同HMAC的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆