I am Hack Sparrow
Captain of the Internets.

How to Generate md5, sha1, sha512, sha256 Checksum Hashes in Node.js

Checksums in Node.js are generated using the crypto library's createHash() method. The usage format is this:

crypto.createHash(algo)

Where algo is the algorithm of your choice - md5, sha1, sha512, sha256 etc. The algorithms supported are entirely dependent on the OpenSSL version on your machine.

Here are some examples of generating hashes for string inputs:

var crypto = require('crypto');

var md5 = crypto.createHash('md5').update('Apple').digest("hex");
// 9f6290f4436e5a2351f12e03b6433c3c
var sha1 = crypto.createHash('sha1').update('Apple').digest("hex");
// 476432a3e85a0aa21c23f5abd2975a89b6820d63
var sha256 = crypto.createHash('sha256').update('Apple').digest("hex");
// f223faa96f22916294922b171a2696d868fd1f9129302eb41a45b2a2ea2ebbfd

In case you want to generate the checksum hash of a file:

var crypto = require('crypto');
var fs = require('fs');

// change the algo to sha1, sha256 etc according to your requirements
var algo = 'md5';
var shasum = crypto.createHash(algo);

var file = './kitten.jpg';
var s = fs.ReadStream(file);
s.on('data', function(d) { shasum.update(d); });
s.on('end', function() {
    var d = shasum.digest('hex');
    console.log(d);
});

There it is, generating checksums in Node.js - very simple and easy.

2 Responses to “How to Generate md5, sha1, sha512, sha256 Checksum Hashes in Node.js”

  1. kumar says:

    Code was helpful.
    Thanks

  2. Roberto says:

    Hi,
    this function is pretty good, i would like to know if is possible call this function from a classic ASP page, and also if is possible send to the function the path and the name of the file to digest, and obliviosly get back the hash generated.

Make a Comment