Node.js

Creating a hash in Node.js

Introduction

We require hashes everywhere, like setting the password in database as hash instead of plain text password, to check whether if file is tampered or not during transmission or checking integrity of file or messages transferred over network, etc.

This small article will give detailed look at creating hash from Node.js core crypto module and later in the article, it shows how we can use the npm modules for same purpose.

Using Core Module

Node.js provides built-in core module crypto to do cryptography functionality. This core module provides the wrappers on OpenSSL functions.

To make use of these crypto functions, you will need to keep in mind following-

  • you will need to have openssl installed on your machine. Many linux based machines has openssl installed by default.
  • All functionality depends on version of OpenSSL installed as Node.js just provides wrapper functions on top of OpenSSL functions

You can check for the which algorithms provided with following command –openssl dgst -h, upon executing command you will get following-

$ openssl version
OpenSSL 0.9.8zh 14 Jan 2016

$ openssl dgst -h
unknown option '-h'
options are
-c              to output the digest with separating colons
-d              to output debug info
-hex            output as hex dump
-binary         output in binary form
-sign   file    sign digest using private key in file
-verify file    verify a signature using public key in file
-prverify file  verify a signature using private key in file
-keyform arg    key file format (PEM or ENGINE)
-signature file signature to verify
-binary         output in binary form
-hmac key       create hashed MAC with key
-engine e       use engine e, possibly a hardware device.
-md5            to use the md5 message digest algorithm (default)
-md4            to use the md4 message digest algorithm
-md2            to use the md2 message digest algorithm
-sha1           to use the sha1 message digest algorithm
-sha            to use the sha message digest algorithm
-sha224         to use the sha224 message digest algorithm
-sha256         to use the sha256 message digest algorithm
-sha384         to use the sha384 message digest algorithm
-sha512         to use the sha512 message digest algorithm
-mdc2           to use the mdc2 message digest algorithm
-ripemd160      to use the ripemd160 message digest algorithm

As you can see from above, from line 19 to line 29, it shows the algorithms available.

So, basically, you can access functions such as hash, hmac, ciper, decipher, sign, etc.

For this article, we will make use of hash function and how we generate using Node.js crypto module.

Following are steps –
1. Load crypto module
2. Create the hash object with specified algorithm
3. Set the data to be hashed, this can be string, file object, buffer object
4. Generate the hash in required format

For creating the hash object we can use following algorithms –
– MD5 (Message Digest 5)
– SHA1 (Simple Hash Algorithm)
– SHA256 (Simple Hash Algorithm -2 for 256 bits)

Each algorithms has pros and cons and can be used according to need of application.

Lets go from each and every stepes of creating hash-

Step-1: Load crypto module

var crypto = require(‘crypto’)

Step-2: Create Hash object from crypto

var hash = crypto.createHash([algorith-to-be-used])

Please note, how hash object is created with factory function provided by the cypto variable and not to be created with new keyword.
For creating the hash object, you need to provide the algorithm to be used, mostly following three are used md5, sha1, sha256. You can use any algorithm which your OpenSSL provides on your machine.

For e.g.
var hash = crypto.createHash(‘md5’)
var hash = crypto.createHash(‘sha1’)
var hash = crypto.createHash(‘sha256’)

Step-3: Set the data to be hashed
Now, on hash object, we need to set data to be hashed to which we have to generate hash. This can be string, file object, along with data we need to specify the encoding type for data, this usually utf-8 or can be binary, ascii

For this, we need to use update() function on hash object,

hash.update([data to be hashed], [encoding-type] )

For.e.g
hash_update = hash.update(‘my super secret data’, ‘utf-8’)

Step-4: Create the hash digest in required format
Once we set the data to be hashed, now we can easliy create the has with digest funciton on the object which is return from update() call. This digest takes parameter which asks for in which format the hash to be generated, this can be hex. ….

generated_hash= hash_update.digest([format])

After the above step, generated_hash variable will have the final hash on data provided and algorighm used.

tldr;

Now, above steps can be merged into the single chained calls, as follows, which makes code one-liner-

generated_hash = require(‘crypto’)
.createHash('md5')
.update(‘my super secret data’, 'utf8')
.digest('hex')

Generating hash for the file

For generating for file, we need to read chunks of file stream data and create hash from that chunk accordingly.

var md5sum = crypto.createHash('md5');

var s = fs.ReadStream(filename);
s.on('data', function(d) {
md5sum.update(d);
});

s.on('end', function() {
var generated_hash = md5sum.digest('hex');
console.log( 'Generated Hash for file ' +generated_hash);
});

Using the npm module

Now, above steps can be simplified with use of the npm modules available. such as md5 or sha1 which wil generate hash using md5 and sha1 algorithm.

These modules does not uses the funcitons provided from crypto module rather, it implements using other crypto libraries such as CryptoJS
And also these modules simplies steps of creating hash with just one simple function.

Using md5

First, you will need this module with following command, do it your Node project directory –
npm install md5

Following code listing shows the usage-

var md5 = require(‘md5’);
var msg = “super secret code”;
var hash = md5(msg);

Using sha1

Install module with following command, again execute same in project directory-
npm install sha1

Following code listing shows the usage-

var sha1 = require(‘sha1’);
var msg = “super secret code”;
var hash = sha1(msg);
Reference: Creating a hash in Node.js from our WCG partner Abhijeet Sutar at the ajduke’s blog blog.

Abhijeet Sutar

Abhijeet (ajduke) is self-taught, self-organized software developer. His current go to language is Java and also he is exploring other languages such as Scala, Ruby.
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Back to top button