【发布时间】:2023-01-10 11:20:27
【问题描述】:
我正在尝试将此代码从 Javascript 转换为 Python3:
import crypto from 'crypto';
const secretKey = 'NgTriSCalcUltAbLoGResOnOuSeAKeSTraLryOuR'
function verifySignature(rawBody) {
const calculatedSignature = crypto
.createHmac('sha256', secretKey)
.update(rawBody, 'utf8')
.digest('base64');
return calculatedSignature;
}
console.log(verifySignature('a'));
使用该代码,我得到了这个输出:vC8XBte0duRLElGZ4jCsplsbXnVTwBW4BJsUV1qgZbo=
所以我试图使用这段代码将相同的函数转换为 Python:
更新
import hmac
import hashlib
message = "a"
key= "NgTriSCalcUltAbLoGResOnOuSeAKeSTraLryOuR"
hmac1 = hmac.new(key=key.encode(), msg=message.encode(), digestmod=hashlib.sha256)
message_digest1 = hmac1.hexdigest()
print(message_digest1)
但我收到此错误:AttributeError: 'hash' 对象没有属性 'digest_size'
有人能告诉我在 Python 中实现相同输出我缺少什么吗?
谢谢! :)
【问题讨论】:
-
带有密钥的 HMAC 与没有密钥的原始 SHA256 散列不同。 base64 编码的摘要与作为字节的原始摘要不同。
标签: javascript python python-3.x cryptojs