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

1

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.