如何解决为什么crypto.subtle.digest返回一个空对象
我有以下简单代码:
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)
返回一个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。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。