HMAC SHA-512 哈希函数等效于 node.js

HMAC SHA-512 hashing function equivalent in node.js

我目前在 Python -

中有这个片段
import base64
import hashlib
import hmac
def hash_hmac(self, key, data):
    res = hmac.new(base64.b64decode(key), data.encode(), hashlib.sha512).digest()
    return res

我正在尝试在 Node.js 中复制它,但很难获得正确的哈希值。

const crypto = require('crypto')
const hashHmac = (key, message) => {
  return crypto.createHmac('sha512', Buffer.from(key, 'base64').toString('utf-8'))
        .update(message)
        .digest()
        .toString('base64') 
}

测试用例: 键:'7pgj8Dm6' 消息:'Test[=27=]Message'

对于 python 片段,哈希是

69H45OZkKcmR9LOszbajUUPGkGT8IqasGPAWqW/1stGC2Mex2qhIB6aDbuoy7eGfMsaZiU8Y0lO3mQxlsWNPrw==

对于js片段,哈希是

OhaJU9IibhhjIjz3R7FmodgOBUPjwhndXX8gn0r2rRzjQvCJl4T40rHXKw3o6Y2JQ5fVHTeStu8K1DRMWxMGBg==

我的 base64 编码有问题吗?

在NodeJS代码中,key是先Base64解码,再UTF-8解码。由于密钥包含UTF-8未定义的字节序列,因此已损坏。

任意二进制数据,例如密文、散列或密钥(至少如果是随机生成的),必须以二进制或 binary-to-text encoding like Base64 must be used (and not a character set encoding like UTF-8) if they are to be converted to a string, see also here.

存储

在发布的示例中,根本不需要将缓冲区转换为字符串。密钥可以简单地直接作为缓冲区传递,s。 crypto.createHmac(),即如下:

var hmac = crypto.createHmac('sha512', Buffer.from(key, 'base64'));

有了这个,NodeJS 代码 returns 与 Python 代码的结果相同。

如果您安装了 NodeJs:

 echo "console.log(require('crypto').createHmac('sha512', 'nonbase64key').update('password').digest('hex'))" | node

在python中等价于:

python3 -c 'import hashlib;import base64;import hmac;print(hmac.new(b"nonbase64key", "password".encode(), hashlib.sha512).hexdigest())'

而等效的纯 shell 命令是:

echo -n "password" | openssl sha512 -hmac "nonbase64key"