Make Better Things

I like to make better things.

How to calculate MD5 hash in node.js

First a little intro to Hashes, for those who are very new to Hashes

What is a Hash?

A hash is a fixed-length string of bits that is procedurally and deterministially generated from some arbitrary block of source data. Some important properties of these hashes (the type useful for cryptography) include:

Fixed length: This means that, no matter what the input, the length of the hash is the same. For example, md5 hashes are always 128 bits long whether the input data is a few bits or a few gigabytes.

Deterministic: For the same input, you should expect to be able to calculate exactly the same hash. This makes hashes useful for checksums.

Collision-Resistant: A collision is when the same hash is generated for two different input blocks of data. Hash algorithms are designed to be extremely unlikely to have collisions — just how unlikely is a property of the hash algorithm. The importance of this property depends on the use case.

Unidirectional: A good hash algorithm is easy to apply, but hard to undo. This means that, given a hash, there isn’t any reasonable way to find out what the original piece of data was.

Some of the most common hash types are SHA1 and MD5

Now how to calculate Hash in Node.js

Node.js have a module named Crypto, which has a method called createHash which allows you to calculate a hash. Its only argument is a string representing the hash This example finds the md5 hash for the string, “I love Node.js”

var crypto = require('crypto');
var name = 'I love Node.js';
var hash = crypto.createHash('md5').update(name).digest("hex");

The update method is used to push data to later be turned into a hash with the digest method. update can be invoked multiple times to ingest streaming data, such as buffers from a file read stream. The argument for digest represents the output format, and may either be “binary”, “hex” or “base64″. It defaults to binary.

Category: node.js

Tagged: , , ,

Leave a Reply