I've run this example that comes from MDN doc
const text = 'An obscure body in the S-K System, your majesty. The inhabitants refer to it as the planet Earth.';
async function digestMessage(message) {
const msgUint8 = new TextEncoder().encode(message); // encode as (utf-8) Uint8Array
const hashBuffer = await crypto.subtle.digest('SHA-256', msgUint8); // hash the message
const hashArray = Array.from(new Uint8Array(hashBuffer)); // convert buffer to byte array
const hashHex = hashArray.map(b => b.toString(16).padStart(2, '0')).join(''); // convert bytes to hex string
return hashHex;
}
const digestHex = await digestMessage(text);
console.log(digestHex);
I understand the basic usage shown in the example.
However, I don't know how to generates a digest of the given file/blob. I've tried this
const hashBuffer = crypto.subtle.digest('SHA-256', file);
click https://jsfiddle.net/5dn4bjfw/ to see full version.
and got this error.
The provided value is not of type '(ArrayBuffer or ArrayBufferView)'
What should I do?
crypto.subtle.digest() requires an ArrayBuffer or ArrayBufferView.
File can be viewed as ArrayBuffer via file.arrayBuffer().
The function in the example above should be async as in MDN example and use await for all the calls that return Promises.
async function myFunction(){
const finput = document.getElementById('fileinput');
const file = finput.files[0];
const arrayBuffer = await file.arrayBuffer();
const hashBuffer = await crypto.subtle.digest('SHA-256', arrayBuffer); // hash the message
console.log(hashBuffer);
const hashArray = Array.from(new Uint8Array(hashBuffer)); // convert buffer to byte array
const hashHex = hashArray.map(b => b.toString(16).padStart(2, '0')).join('');
console.log(hashHex);
}
If you need an ArrayBuffer, you might able to use the arrayBuffer API
https://developer.mozilla.org/en-US/docs/Web/API/Blob/arrayBuffer
blob.arrayBuffer().then(buffer => {
//your encoding functions here, pass buffer to the function
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With