为什么 crypto.subtle.digest return 是一个空对象

Why does crypto.subtle.digest return an empty Object

我有以下简单代码:

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

crypto.subtle.digest(algorithm, data) returns 满足 ArrayBufferPromise 包含摘要。

JSON.stringify() expects a JavaScript object. So the ArrayBuffer must be converted accordingly. One possibility is to convert the contents of the buffer into a or Base64 编码的字符串并在 JavaScript 对象中使用结果,例如

// from: 
function buf2hex(buffer) { // buffer is an ArrayBuffer
    return Array.prototype.map.call(new Uint8Array(buffer), x => ('00' + x.toString(16)).slice(-2)).join('');
}

// from 
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.