我希望在 Javascript 中使用 SHA256 在本地散列一个字符串。我一直在环顾四周,认为会有某种官方库或函数,但我发现的只是大量不同的项目,每个项目都有不同的脚本,而且我不太确定要信任的脚本(因为我不是专家,绝对没有资格评估它们)或如何实施它们。 编辑:我需要文本输出,而不是十六进制,对不起,如果我在发布原始问题时没有解释。
这是我迄今为止尝试过的:
async function sha256(message) {
// encode as UTF-8
const msgBuffer = new TextEncoder('utf-8').encode(message);
// hash the message
const hashBuffer = await crypto.subtle.digest('SHA-256', msgBuffer);
// convert ArrayBuffer to Array
const hashArray = Array.from(new Uint8Array(hashBuffer));
// convert bytes to hex string
const hashHex = hashArray.map(b => ('00' + b.toString(16)).slice(-2)).join('');
console.log(hashHex);
return hashHex;
}
sha256(passwordInput);
Run Code Online (Sandbox Code Playgroud)
未捕获(承诺)类型错误:无法读取未定义的属性“摘要”
我是 javascript 新手,我愿意接受所有建议,所以是的。
尽管您的大部分建议都有效,但对于那些希望使用 Web Crypto API 的人来说,答案就在第 5 行。我需要crypto.subtle.digest改为window.crypto.subtle.digest