Reputation: 63
I am hashing a blob by reading it first using FileReader API in Javascript. The library I am using is JSHashes.
var fileReaderForHash = new FileReader();
fileReaderForHash.readAsArrayBuffer(zipBlob);
fileReaderForHash.onload = () => {
var zipFileHash = new
Hashes.SHA256().hex(fileReaderForHash.result);
console.log(zipFileHash);
postRef.update({hash:zipFileHash});
}
But when I do "sha256sum zipfile.zip" in the terminal the hash obtained doesn't match with the one that was logged. I have also tried all other read methods of the FileReader API. What should I do differently?
Upvotes: 0
Views: 549
Reputation: 401
The explanation provided by t.niese is correct. I am posting its solution.
I solved this using the sha256sum library from GitHub.
Here is the code:
.....
// import the library
var hash = sha256.hex(zipArrayBuffer); // input arraybuffer
console.log(hash); // displays hash
zipBlob = new Blob([new Uint8Array(zipBlob)]); // convert to blob for reading
.....
Upvotes: 1
Reputation: 40872
I know that this "answer" does not give a solution but it explains why this does not work.
The current version of the JSHashes library (1.0.7) requires a string as input, but you provide an ArrayBuffer
.
Internaly when hex
is called, this code is executed, where s
is your ArrayBuffer and utf8
default to true
:
function rstr(s, utf8) {
s = (utf8) ? utf8Encode(s) : s;
return binb2rstr(binb(rstr2binb(s), s.length * 8));
}
function utf8Encode(str) {
var x, y, output = '',
i = -1,
l;
if (str && str.length) {
// .... some other code
}
return output;
}
And utf8Encode
will always return an empty string for an ArrayBuffer because it has no length
property. Even if you change utf8
to false
the problem will persist because it will still expect a string and fail at another place because of the missing length
.
And the sha256 for the empty string is e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855
and thats the sha256 you will get for every file.
Upvotes: 0