How to create a MD5 hash in Node.js?

November 15, 2020 - 3 min read

To create a MD5 hash, you need to import or require the crypto module and use the createHmac() method in Node.js.

First, let's require the crypto module in Node.js,

// get crypto module
const crypto = require("crypto");

Now let's make a string that needs to be hashed using the md5 hashing algorithm and also make a secret or a salt string that needs to be provided with a hashing function to add more secrecy 👽.

// get crypto module
const crypto = require("crypto");

// string to be hashed
const str = "I need to be hashed using MD5😃!";

// secret or salt to be hashed with
const secret = "This is a secret 🤫";

Now we need to call the createHmac() (The Hmac in the method stands for Keyed-Hashing for Message Authentication 🌟) method to create the hasher and pass the hashing algorithm's name we need to use as the first argument and the secret or salt string as the second argument to the method. In our case, it is md5 as the first argument and the secret as the second argument to the method. It can be done like this,

// get crypto module
const crypto = require("crypto");

// string to be hashed
const str = "I need to be hashed using MD5😃!";

// secret or salt to be hashed with
const secret = "This is a secret 🤫";

// create a md5 hasher
const md5Hasher = crypto.createHmac("md5", secret);

After creating the hasher, you need to use the update() method in the hasher and pass the string to hash the string. It can be done like this,

// get crypto module
const crypto = require("crypto");

// string to be hashed
const str = "I need to be hashed using MD5😃!";

// secret or salt to be hashed with
const secret = "This is a secret 🤫";

// create a md5 hasher
const md5Hasher = crypto.createHmac("md5", secret);

// hash the string
const hash = md5Hasher.update(str);

It is called update() since it also accepts a continuous stream of data like a buffer. Finally, after calling the update() method we need to define the output format for the hash. It can be hex, binary, or base64. We can define it using the digest() method on the object returned from the update() method like so,

// get crypto module
const crypto = require("crypto");

// string to be hashed
const str = "I need to be hashed using MD5😃!";

// secret or salt to be hashed with
const secret = "This is a secret 🤫";

// create a md5 hasher
const md5Hasher = crypto.createHmac("md5", secret);

// hash the string
// and set the output format
const hash = md5Hasher.update(str).digest("hex");

// A unique md5 hash 😃
console.log(hash); // 1c211d131453e023d101c40f2c3372e0

We have now successfully hashed our string using the md5 algorithm ✅.

See the code snippet live in repl.it.

Feel free to share if you found this useful 😃.