How to use hash_hmac function in node js

时间秒杀一切 提交于 2019-12-14 03:12:02

问题


Recently I have used same code on PHP and it's working fine but when I tried Node Js, it's not working for me. Please check once:

PHP

$signature = $ACCID . "POST" . strtolower(urlencode($url)).$requestContentBase64String; 
$hmacsignature = base64_encode(hash_hmac("sha256", $signature, base64_decode($APIKey), true)); 

NODE CODE :

var signature = ACCID+"POST"+encodeURI(url).toLowerCase()+requestContentBase64String; 
var hmacsignature = base64.encode(crypto.createHmac('sha256', APIKey).update(signature).digest('base64'))

Please check what's wrong in this code.


回答1:


Your second line has two mistakes:

  1. PHP APIKey is BASE64_DECODE(APIKey) while in Node.js code it is just APIKey
  2. PHP hmacsignature is BASE64(HEX(HMAC)) while in Node.js code it is BASE64(BASE64(HMAC))

Try this:

var hmacsignature = crypto.createHmac('sha256', Buffer.from(APIKey, 'base64')).update(signature).digest('base64')


来源:https://stackoverflow.com/questions/52148156/how-to-use-hash-hmac-function-in-node-js

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