无法在node.js中从PHP重现sha512 hmac

时间:2015-05-28 14:04:25

标签: node.js hmac

我有一些生成hmac的PHP代码如下:

<?php
$secret = "7pgj8Dm6";
$message = "Test\0Message";
echo base64_encode(hash_hmac('sha512', $message, base64_decode($secret), true))."\n";
echo "69H45OZkKcmR9LOszbajUUPGkGT8IqasGPAWqW/1stGC2Mex2qhIB6aDbuoy7eGfMsaZiU8Y0lO mQxlsWNPrw==\n";
?>

当我尝试在node.js中生成类似的代码时,我获得了与我想要的不同的base64编码结果,并且我无法弄清楚原因。

var hmac = function(msg, secret){
  var s = (new Buffer(secret, 'base64')).toString('utf8');
  var hmac = require('crypto').createHmac('sha512',s);
  hmac.update(msg);
  return hmac.digest('base64');
};

var secret = "7pgj8Dm6";
var message = "Test\0Message";
var wanted = "69H45OZkKcmR9LOszbajUUPGkGT8IqasGPAWqW/1stGC2Mex2qhIB6aDbuoy7eGfMsaZiU8Y0lO3mQxlsWNPrw==";
var got = hmac(message, secret);
if(wanted === got){
  console.log('All is fine.');
}else{
  console.log('Hash is wrong :(');
}
console.log('wanted:\t'+wanted);
console.log('got:\t'+got);

我的动机是api,我想玩一点。

1 个答案:

答案 0 :(得分:1)

好的,我明白了。问题是我在toString函数中创建的Buffer上调用hmac。当我删除它时,一切正常。

var hmac = function(msg, secret){
  var s = new Buffer(secret, 'base64');
  var hmac = require('crypto').createHmac('sha512',s);
  hmac.update(msg);
  return hmac.digest('base64');
};