【问题标题】:Why does crypto.subtle.digest return an empty Object为什么 crypto.subtle.digest 返回一个空对象
【发布时间】:2020-12-23 10:56:31
【问题描述】:
我有以下简单的代码:
inputBytes = new TextEncoder().encode(inputString)
hashBytes = await window.crypto.subtle.digest("SHA-256", inputBytes)
console.log((typeof hashBytes) + ": " + JSON.stringify(hashBytes))
为什么结果是一个空对象?
我怎样才能得到真正的结果?
这太奇怪了,非常感谢任何帮助
https://codepen.io/JhonnyJason/pen/QWNOqRJ
【问题讨论】:
标签:
hash
cryptography
webcrypto-api
【解决方案1】:
crypto.subtle.digest(algorithm, data) 返回一个 Promise,该 ArrayBuffer 包含摘要。
JSON.stringify() 需要一个 JavaScript 对象。所以ArrayBuffer 必须进行相应的转换。一种可能性是将缓冲区的内容转换为hexadecimal 或Base64 编码字符串,然后在 JavaScript 对象中使用结果,例如
// from: https://stackoverflow.com/a/40031979/9014097
function buf2hex(buffer) { // buffer is an ArrayBuffer
return Array.prototype.map.call(new Uint8Array(buffer), x => ('00' + x.toString(16)).slice(-2)).join('');
}
// from https://stackoverflow.com/a/11562550/9014097
function buf2Base64(buffer) {
return btoa(String.fromCharCode.apply(null, new Uint8Array(buffer)));
}
async function test() {
var inputString = "The quick brown fox jumps over the lazy dog";
inputBytes = new TextEncoder().encode(inputString);
hashBytes = await window.crypto.subtle.digest("SHA-256", inputBytes);
console.log(JSON.stringify({hash: buf2hex(hashBytes)})); // {"hash":"d7a8fbb307d7809469ca9abcb0082e4f8d5651e46d3cdb762d02d0bf37c9e592"}
console.log(JSON.stringify({hash: buf2Base64(hashBytes)})); // {"hash":"16j7swfXgJRpypq8sAguT41WUeRtPNt2LQLQvzfJ5ZI="}
}
test();
这给出了正确的结果,例如可以验证here.