Lenny
Lenny

Reputation: 167

Why does crypto.subtle.digest return an empty Object

I have following simple Code:

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

Why is the result an empty Object? How can I get the real result?

This is so weird, any help very appreciated

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

Upvotes: 4

Views: 8904

Answers (1)

Topaco
Topaco

Reputation: 49351

crypto.subtle.digest(algorithm, data) returns a Promise that fulfills with an ArrayBuffer containing the digest.

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 hexadecimal or Base64 encoded string and use the result in a JavaScript object, e.g.

// 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();

This gives the correct result, as can be verified e.g. here.

Upvotes: 7

Related Questions