我想使用客户端密钥HMAC SHA256
对规范化的请求进行哈希处理,并对结果进行base64编码。我在python
和typeScript
中得到了不同的结果。我的目标是在python
中获得typeScript
的结果。该怎么做?
我能够将hashlib.sha256
(Here is my approach)转换为等效的typeScript
,但不确定hmac.new
Python代码:
import hashlib
import hmac
import base64
request = "Hello World";
secret = "MySecret"
requestBytes = bytes(request.encode('utf-8'))
secretBytes = bytes(secret.encode('utf-8'))
hmacConversion = hmac.new(secretBytes, requestBytes, digestmod=hashlib.sha256).digest()
signature = base64.b64encode(hmacConversion)
print(signature)
输出:
b'm4nZSWE3Y/tPXToy/0cJMGpR2qpsXgCnF3tsSiZtYt0='
TypeScript代码:
var secret = "Hello World";
var body = "MySecret";
var hmac = crypto.createHmac("sha256", secret)
.update(Buffer.from(body, 'utf-8'))
.digest('hex');
console.log(hmac);
var hmac2 = crypto.createHmac("sha256", secret)
.update(body, 'utf-8')
.digest('hex');
console.log(hmac2);
输出:
f1f157335b0982cbba94290163d61582a87352817788b793238817dd631c26d4
答案 0 :(得分:0)
我找到了答案。我花了1天的时间,这是一个非常愚蠢的错误。希望这可以节省某人的一天。
代码:
var crypto = require('crypto');
// Below was silly mistake. In my question those parameters are swapped.
var body = "Hello World";
var secret = "MySecret";
var hmac = crypto.createHmac("sha256", secret )
.update(body)
.digest('base64')
console.log(hmac);
输出:
m4nZSWE3Y/tPXToy/0cJMGpR2qpsXgCnF3tsSiZtYt0=