【发布时间】:2021-03-10 03:38:03
【问题描述】:
主要问题
我有以下一小段遗留代码,我正试图将其从 Python(仅使用标准库)移植到 JavaScript——从我假设它创建 abc 字符串的 SHA-1 摘要的方法名称来看
import hashlib
import hmac
print(hmac.new(b"abc", None, hashlib.sha1).hexdigest())
我在浏览器中用JS搜索了怎么做,发现the following code in the Mozilla documentation
var msgUint8 = new TextEncoder().encode('abc');
var hashBuffer = await crypto.subtle.digest('SHA-1', msgUint8);
var hashArray = Array.from(new Uint8Array(hashBuffer));
var hashHex = hashArray.map(b => b.toString(16).padStart(2, '0')).join('');
console.log(hashHex)
问题是,它们产生了两个完全不同的结果,我不知道为什么:
-
cc47e3c0aa0c2984454476d061108c0b110177ae- Python -
a9993e364706816aba3e25717850c26c9cd0d89d- JavaScript
我尝试将b"abc" 的字节与new TextEncoder().encode('abc') 返回的字节进行比较,它们完全相同:0x61 0x62 0x63,所以问题出在其他地方,我不知道在哪里。
我需要 JavaScript 代码来返回 Python 代码返回的内容。有什么想法吗?
另外
我的最终目标是实际移植这个代码(注意b"hello"而不是None):
print(hmac.new(b"abc", b"hello", hashlib.sha1).hexdigest())
所以,如果您对此也有任何想法 - 我将不胜感激!
【问题讨论】:
-
您需要特定的库(因为您的示例使用 WebCrypto)还是与使用的 JavaScript 库无关?
-
@Topaco 理想情况下,它可以在 Firefox 和 Chrome 上运行而无需外部依赖
标签: javascript python cryptography sha1