Reputation: 17280
I am trying to get the checksum/hash from a file upload on my webpage.
I am currently able to upload the file via my browser then calculate the hash using the node.js crypto library. I first convert the blob to a data Url.
export function calculateHash(dataUrl, type){
const sha1sum = crypto.createHash('sha1').update(dataUrl).digest("hex");
console.log('Hash sum is ' + sha1sum);
}
Result: 66b8bdd2d1d49f708722c15b26409bc072096697
When i calculate the hash manually from the windows command prompt using the following command..
fciv.exe 1_1.wav -sha1
Result: b06071b13a1b50cd2976ed7bb4180f6963e8db8e
I would like to get the same checksum result from the data url in my browser as doing the manual check from the command prompt.
Is this possible?
Upvotes: 1
Views: 7679
Reputation: 20248
A data url looks like data:image/png;base64,<BASE-64 DATA>
. You would need to extract the BASE-64 DATA part, decode base64 and then run your hashing algorithm. Or - if you want to perform the hashing in the browser - use the FileReader API:
function calculateHash(file, callback) {
let reader = new FileReader();
reader.onload = function(event) {
let file_sha1 = sha1(reader.result);
callback(file_sha1);
};
reader.readAsArrayBuffer(file);
}
let input = document.getElementById("input-file"),
info = document.getElementById("info");
input.addEventListener("change", function(event) {
let file = input.files[0];
if (file) {
calculateHash(file, function(file_sha1) {
info.textContent = file_sha1;
});
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/js-sha1/0.6.0/sha1.min.js"></script>
<input id="input-file" type="file">
<div id="info"></div>
Requires js-sha1 (npm install js-sha1
).
Credit to: How to checksum the file to be uploaded with javascript?
Upvotes: 4