Reputation: 629
I am probably not using the crypto
module correctly, maybe someone can help me out.
The goal is to find the sha-256 hash of a file dropped in a dropzone
. The problem is that the hash being returned is different from online hash checkers (which are returning the seemingly correct values). Here is my code:
const crypto = require("crypto");
const hash = crypto.createHash("sha256");
handleOnDrop = file => {
hash.update(file);
const hashOutput = hash.digest("hex");
console.log(hashOutput);
};
Crypto docs - https://nodejs.org/api/crypto.html#crypto_node_js_crypto_constants
I am fairly sure the hash values I am getting from this code is not just the file name, I checked a few permutations with the online checkers.
Any ideas? Thanks!
Upvotes: 0
Views: 617
Reputation: 869
Dropzone events return a File class object, this object is based on the Blob class and doesn't provide direct access to the data of the file. In order to use the data in the file, you must use the FileReader class as outlined in the Mozilla examples
Crypto is expecting a buffer when you call hash.update
, but file
isn't a Buffer like it would be in these examples. Dropping a Blob into hash.update
probably doesn't have the behavior you are expecting.
So, assuming you're using WebPack to provide access to the Node standard libraries, your code should need to do something like this:
handleOnDrop = ((file) => {
const reader = new FileReader();
reader.readAsArrayBuffer(file);
reader.onload = ((event) => {
hash.update(Buffer.from(event.target.result));
const hashOutput = hash.digest("hex");
console.log(hashOutput);
});
});
Upvotes: 1