无法在 node.js 中从 PHP 重现 sha512 hmac
Cannot reproduce sha512 hmac from PHP in node.js
我有一些 PHP 生成 hmac 的代码如下:
<?php
$secret = "7pgj8Dm6";
$message = "Test[=12=]Message";
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[=13=]Message";
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);
我的动机是 anxpro api,我想用它玩一下。
好的,我明白了。问题是我在 hmac
函数中创建的 Buffer
上调用 toString
。当我删除它时,一切正常。
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');
};
我有一些 PHP 生成 hmac 的代码如下:
<?php
$secret = "7pgj8Dm6";
$message = "Test[=12=]Message";
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[=13=]Message";
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);
我的动机是 anxpro api,我想用它玩一下。
好的,我明白了。问题是我在 hmac
函数中创建的 Buffer
上调用 toString
。当我删除它时,一切正常。
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');
};