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);
      };
    });
}