Node.js: Generating md5, sha1, sha512, sha256 checksum hashes
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
If you don't pass 'hex' to the .digest()
method, it will return a Buffer.
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.