How to Hash a File in JavaScript/TypeScript

We can use JavaScript's FileReader object which is part of the Web API in order to hash our file. FileReader allows us to asynchronously "read the contents of the file" from a user's computer. We will also leverage the library CryptoES for creating a word array and hashing.

We create a function called createFileHash where we will pass the file and inside that function we will create a promise which will leverage the FileReader object which we have instantiated and then we proceed to read the file contents using readAsArrayBuffer.

We use the onload event handler so that when the file is loaded we can use CryptoES' wordArray object in order to create aa 32-bit array and cast as an ArrayBuffer data type.

We then take the result of the word array and hash the file using CryptoES' SHA256 hashing algorithm and output the resulting hash as a string. Finally, we place the resulting hash inside resolve and return it when the promise is resolved.

function createFileHash(file: File): Promise<string> {
    return new Promise((resolve) => {
      const reader = new FileReader();
      let result = '';
      reader.readAsArrayBuffer(file);
      reader.onload = () => {
        const fileWordArray = CryptoES.lib.WordArray.create(
          reader.result as ArrayBuffer
        );
        const fileHash = CryptoES.SHA256(fileWordArray).toString();        
        resolve(fileHash);
      };
    });
}

This blog post was originally published on my blog Communicode, where I write about different tech topics.

TypeScriptJavaScript
Avatar for Muhammad Asfour

Written by Muhammad Asfour

I am a Full Stack Developer with over 5 years of experience. I have worked with different tech stacks such as: Groovy/Java, PHP, .NET/.NET Core (C#), Node.js, React, Angular, and Vue.

Loading

Fetching comments

Hey! 👋

Got something to say?

or to leave a comment.