2

I am trying to perform SHA256 hash on a file content using javascript.

I get the file using the following function

var fileReader = new FileReader();
var fileByteArray = [];
fileReader.onload = function(evt) {
    if (evt.target.readyState == FileReader.DONE) {
        var arrayBuffer = evt.target.result,
        array = new Uint8Array(arrayBuffer);
        fileHash = generateHashOfFileContent(array); 
        console.log('fileHash1: ' + fileHash);
    }
}
fileReader.readAsArrayBuffer(this.files[0]);

And the hash function is

function generateHashOfFileContent(fileData){
  var bitArray = sjcl.hash.sha256.hash(fileData);
  var digest_sha256 = sjcl.codec.hex.fromBits(bitArray);
  console.log("Sha256 "+digest_sha256);
  return digest_sha256;
}

But it produce wrong hash data when I select a binary file

I can only produce actual hash using a text file and change the fileReader.readAsArrayBuffer(this.files[0]); -------> fileReader.readAsText(this.files[0]);

Can someone help me to figure out the problem

iOS-Developer84
  • 654
  • 8
  • 19
  • You need to use Latin1 encoding before hashing: https://stackoverflow.com/questions/53521987/node-buffer-alias-binary-is-latin1 – Raluca Iulia Apr 01 '20 at 16:43

1 Answers1

1

You should convert your TypedArray to bitArray:

var fileReader = new FileReader();
var fileByteArray = [];
fileReader.onload = function(evt) {
    if (evt.target.readyState == FileReader.DONE) {
        var arrayBuffer = evt.target.result,
        array = new Uint8Array(arrayBuffer);
        let bitArray = sjcl.codec.bytes.toBits(array)
        fileHash = generateHashOfFileContent(bitArray); 
        console.log('fileHash1: ' + fileHash);
    }
}
fileReader.readAsArrayBuffer(this.files[0]);

See https://github.com/bitwiseshiftleft/sjcl/wiki/Codecs