OpenSSL HMAC-SHA1 digest does not match Crypto's

本小妞迷上赌 提交于 2019-12-07 19:01:30

问题


I've spent past 6 hours implementing message signing algorithm.. It does not work AT ALL:

This is PHP code to generate digest:

$payload = "thisisanapple";
$signature = hash_hmac("sha1", $payload, "thisisarandomkey");
$data = base64_encode($signature);
// YzExZWRmZDliMjQzNTZjNzhlNmE3ZTdmMDE3ODJjNmMxMmM4ZTllMQ==

This is JS running on the Node.js server doing the same thing:

var hmac = crypto.createHmac('sha1', "thisisarandomkey");
hmac.update("thisisanapple");
var signature = hmac.digest('base64');
// wR7f2bJDVseOan5/AXgsbBLI6eE=

I have no clue what is wrong here.. I have tries SHA256, but they still differ. I also used a private key generated with OpenSSL, both in plaintext and in base64, still same result (different keys).


回答1:


hash_hmac has four parameters and the last one specifies the output and by default hash_hmac returns hex string, not the raw data. So base64_encode encodes hex string in the PHP code fragment.

This one will work well:

$payload = "thisisanapple";
$signature = hash_hmac("sha1", $payload, "thisisarandomkey", true);
$data = base64_encode($signature);
// wR7f2bJDVseOan5/AXgsbBLI6eE=



回答2:


If you want to duplicate the PHP behaviour in JS, here is the code:

hmac = crypto.createHmac('sha1', 'thisisarandomkey')
signature = hmac.update('thisisanapple')
data = new Buffer(hmac.digest('hex')).toString('base64')


来源:https://stackoverflow.com/questions/19884738/openssl-hmac-sha1-digest-does-not-match-cryptos

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!