Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

javascript

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?

like image 576
PutBere Avatar asked Oct 24 '25 14:10

PutBere


2 Answers

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);
} 
like image 156
Vitalii Avatar answered Oct 27 '25 04:10

Vitalii


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
   });
like image 25
imvain2 Avatar answered Oct 27 '25 02:10

imvain2