0

I am relatively new to JavaScript and I want to get the hash of a file, and would like to better understand the mechanism and code behind the process.

So, what I need: An MD5 or SHA-256 hash of an uploaded file to my website.

My understanding of how this works: A file is uploaded via an HTML input tag of type 'file', after which it is converted to a binary string, which is consequently hashed.

What I have so far: I have managed to get the hash of an input of type 'text', and also, somehow, the hash of an uploaded file, although the hash did not match with websites I looked at online, so I'm guessing it hashed some other details of the file, instead of the binary string.

Question 1: Am I correct in my understanding of how a file is hashed? Meaning, is it the binary string that gets hashed?

Question 2: What should my code look like to upload a file, hash it, and display the output?

Thank you in advance.

Yakko Majuri
  • 448
  • 3
  • 13
  • Check out this topic: https://stackoverflow.com/questions/768268/how-to-calculate-md5-hash-of-a-file-using-javascript – EmirSa Sep 23 '18 at 16:44

1 Answers1

0

Basically yes, that's how it works.
But, to generate such hash, you don't need to do the conversion to string yourself. Instead, let the SubtleCrypto API handle it itself, and just pass an ArrayBuffer of your file.

async function getHash(blob, algo = "SHA-256") {
  // convert your Blob to an ArrayBuffer
  // could also use a FileRedaer for this for browsers that don't support Response API
  const buf = await new Response(blob).arrayBuffer();
  const hash = await crypto.subtle.digest(algo, buf);
  let result = '';
  const view = new DataView(hash);
  for (let i = 0; i < hash.byteLength; i += 4) {
     result += view.getUint32(i).toString(16).padStart(2, '0');
  }
  return result;
}
inp.onchange = e => {
  getHash(inp.files[0]).then(console.log);
};
<input id="inp" type="file">
Kaiido
  • 123,334
  • 13
  • 219
  • 285