为什么 crypto.subtle.digest 返回一个空对象

Len*_*nny 4 hash cryptography webcrypto-api

我有以下简单的代码:

inputBytes = new TextEncoder().encode(inputString)
hashBytes = await window.crypto.subtle.digest("SHA-256", inputBytes)
console.log((typeof hashBytes) + ":  " + JSON.stringify(hashBytes))
Run Code Online (Sandbox Code Playgroud)

为什么结果是空对象?我怎样才能得到真正的结果?

这太奇怪了,非常感谢任何帮助

https://codepen.io/JhonnyJason/pen/QWNOqRJ

Top*_*aco 6

crypto.subtle.digest(algorithm, data)返回Promise满足包含ArrayBuffer摘要的 a 。

JSON.stringify()需要一个 JavaScript 对象。所以ArrayBuffer必须进行相应的转换。一种可能性是将缓冲区的内容转换为十六进制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();
Run Code Online (Sandbox Code Playgroud)

这给出了正确的结果,可以在此处进行验证。