哈希和 HMAC 在 Python 和 JS 中提供不同的输出

问题描述 投票:0回答:1

我正在尝试使用 Crypto JS 将使用 HMAC 编码字符串的 python 代码转换为 JS。但是Python和JS COde中产生的HMAC字符串是不同的。

Python代码

`

import hashlib, json, hmac, secrets

date = "2024-01-16 16:11:11"
nonce = 'ksjdnf5646512'
data = {key:value}
method = 'PATCH'
api = 'api'
content_type = 'application/json'
    
hashed_data = hashlib.sha256(json.dumps(data).encode('utf-8')).digest()
string_to_hash = f"{method}\n{date}\n{api}\n{content_type}\n{nonce}\n{hashed_data}"
hmac_string = str(hmac.new('secretkey'.encode('utf-8'), string_to_hash.encode('utf-8'), hashlib.sha256).hexdigest())

print(json.dumps(data))
print(json.dumps(data).encode('utf-8'))
print(hashlib.sha256(json.dumps(data).encode('utf-8')))
print(string_to_hash)
print(hashed_data)
print(hmac_string)

JS代码

var CryptoJS = require("crypto-js");
date = "2024-01-16 16:11:11"
nonce = 'ksjdnf5646512'
data = {key: value}
method = 'PATCH'
api = 'api'
content_type = 'application/json'
data = JSON.stringify(data)
hashed_data = CryptoJS.SHA256(CryptoJS.enc.Latin1.parse(data))
const string_to_hash = `${method}\n${date}\n${api}\n${content_type}\n${nonce}\n${hashed_data}`;
const hmacString = CryptoJS.enc.Hex.stringify(CryptoJS.HmacSHA256(CryptoJS.enc.Latin1.parse(string_to_hash), CryptoJS.enc.Latin1.parse('secretkey')))
console.log(hmacString)

两种代码生成的 HMAC 字符串不同。我需要它相同。

我尝试在 Crypto JS 中使用不同的加密。我无法修改 python 代码。我可以随心所欲地编写JS代码。我认为这个问题可能是由于 python 和 js 中的库不同造成的

javascript python cryptojs hashlib postman-pre-request-script
1个回答
0
投票

当我使用Python和JS设置

data = {'hello': 100}
时,我得到以下结果:

>>> json.dumps(data)
'{"hello": 100}'
> JSON.stringify(data)
'{"hello":100}'

这些不是相同的字符串。因此,当您运行

hmac
时,您不应期望它们会给出相同的结果。如上所述,您应该只 hmac 一个您知道其确切格式的字符串。

© www.soinside.com 2019 - 2024. All rights reserved.