Saturday, 5 December 2020

Is it feasible to use crypto.subtle.digest to generate a digest of the given file?

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?



from Is it feasible to use crypto.subtle.digest to generate a digest of the given file?

No comments:

Post a Comment