我想用JavaScript重新实现某个用Python编写的API客户端。我无法复制 HMAC SHA256 签名功能。对于某些键,输出是相同的,但对于某些键,输出是不同的。在解码其 Base64 表示后,当密钥由可打印字符组成时,输出似乎是相同的。
Python
#!/usr/bin/env python3
import base64
import hashlib
import hmac
def sign_string(key_b64, to_sign):
key = base64.b64decode(key_b64)
signed_hmac_sha256 = hmac.HMAC(key, to_sign.encode(), hashlib.sha256)
digest = signed_hmac_sha256.digest()
return base64.b64encode(digest).decode()
print(sign_string('VGhpcyBpcyBhIHByaW50YWJsZSBzdHJpbmcuCg==', "my message"))
print(sign_string('dGhlIHdpbmQgb2YgTXQuIEZ1amkK', "my message"))
print(sign_string('pkmNNJw3alrpIBi5t5Pxuym00M211oN86IhLZVT8', "my message"))
JavaScript
<script src="https://cdnjs.cloudflare.com/ajax/libs/crypto-js/3.1.9-1/crypto-js.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/crypto-js/3.1.9-1/hmac-sha256.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/crypto-js/3.1.9-1/enc-base64.min.js"></script>
<script>
function sign_string(key_b64, to_sign) {
key = atob(key_b64)
var hash = CryptoJS.HmacSHA256(to_sign, key);
var hashInBase64 = CryptoJS.enc.Base64.stringify(hash);
document.write(hashInBase64 + '<br>');
}
sign_string('VGhpcyBpcyBhIHByaW50YWJsZSBzdHJpbmcuCg==', "my message")
sign_string('dGhlIHdpbmQgb2YgTXQuIEZ1amkK', "my message")
sign_string('pkmNNJw3alrpIBi5t5Pxuym00M211oN86IhLZVT8', "my message")
</script>
产出
Python
TdhfUQfym16HyWQ8wxQeNVvJKr/tp5rLKHYQSpURLpw=
pQ5NzK3KIWjqc75AXBvWgLK8X0kZvjRHXrLAdxIN+Bk=
8srAvMucCd91CWI7DeCFjxJrEYllaaH63wmVlMk0W+I=
JavaScript
TdhfUQfym16HyWQ8wxQeNVvJKr/tp5rLKHYQSpURLpw=
pQ5NzK3KIWjqc75AXBvWgLK8X0kZvjRHXrLAdxIN+Bk=
31QxOpifnpFUpx/sn336ZmmjkYbLlNrs8NP9om6nPeY=
如您所见,前两个是相同的,而最后一个是不同的。
如何更改 JavaScript 代码以使其行为与 python 代码相同?
互换的青春
相关分类