How to hash files in Node.JS

The process is quite simple actually. Unfortunately ,as much things in Node.js, it works asynchronously, for some applications this will be perfect, but for some others it will be a mess to wait for the freaking hash to do something else, anyway I am not going to discuss that here I actually like Node.js.

Please note that in the following example I am using names of files that exist in my computer and are exactly in the same directory of my program. You will have to provide your own file names.

Here is the code:

const crypto = require("crypto");
const fs = require("fs");

try {

    console.log("");

    hashFile("RSA_1024_Private_Key.pem", "sha256");
    hashFile("RSA_1024_Private_Key.pem", "sha256", "Heavy Metal!");

    hashFile("signData.js", "sha384");
    hashFile("signData.js", "sha384", "Celtic rock!");

    hashFile("container.jpg", "sha512");
    hashFile("container.jpg", "sha512", "Rock'n Roll");

} catch (error) {
    console.log(error);
}

function hashFile(fileName, algorithm, hmacKey = null) {

    let start = Date.now();
    let msg = "";
    let hash = null;
    let inputStream = fs.createReadStream(fileName);

    if (hmacKey == null) {
        msg = algorithm;
        hash = crypto.createHash(algorithm);
    } else {
        msg = algorithm + "hmac";
        hash = crypto.createHmac(algorithm, hmacKey);
    }

    inputStream.on('readable', () => {
        const data = inputStream.read();
        if (data)
            hash.update(data);
        else {
            let end = Date.now();
            console.log(fileName + " [" + msg + "]: " + hash.digest('hex') + " [" + (end - start) + " milliseconds]");
        }
    });

}
Your console output should look similar to this:
Z:\Code\NodeJS>node hashFiles.js

RSA_1024_Private_Key.pem [sha256]: f8f7bd60d8ff7b42b9dc80151f41da8037ca09a3761d2899a1f34ef91a3211c6 [5 milliseconds]
RSA_1024_Private_Key.pem [sha256hmac]: ade8801116545dc79086bc35ca5510cfaf7c8c25baf02d1d177cd056ee1c495b [4 milliseconds]
signData.js [sha384]: ff92db9cdf2f63ebcf7807238a4bff2dcd05353de9a4a1175eff0b79a30ef963a0afc628619bb75a9ca31a5d70535de7 [7 milliseconds]
signData.js [sha384hmac]: bd1c8cff013ffbe170e8d9c084b99299bafd87162df9d37a482ac1f2882bc0dd7c3836c1c48359d1f2837ea9de232e72 [7 milliseconds]
container.jpg [sha512]: d313843f3e5fd78c085184337becc52a46e6a1962215851bc91444681852befbdc0504c8274bb5952fba011d641d690dd62a80d5a5697c3857911aba779efdf8 [15 milliseconds]
container.jpg [sha512hmac]: 87181ffa7eda9cd5a690aa183a1b9313bc2f525232fe879efbd176f269dd3ec39b9ed7250f4420db341743ea3f2ff00b4fe03ed086c19cdec462f463e20814b1 [15 milliseconds]

Z:\Code\NodeJS>
Hope it helps!

Leave a Comment

Your email address will not be published. Required fields are marked *