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

时间:2020-09-04 07:20:33

标签: 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))

为什么结果为空对象? 如何获得真实结果?

这太奇怪了,非常感谢您的帮助

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

1 个答案:

答案 0 :(得分:3)

crypto.subtle.digest(algorithm, data)返回一个Promise,其中包含摘要的ArrayBuffer

JSON.stringify()需要JavaScript对象。因此,ArrayBuffer必须进行相应的转换。一种可能性是将缓冲区的内容转换为hexadecimalBase64编码的字符串,然后在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