How to create a SHA-256 hash in Node.js?

November 14, 2020 - 3 min read

To create a SHA-256 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 sha256 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 😃!";

// secret or salt to be hashed with
const secret = "This is a company 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 sha256 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 😃!";

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

// create a sha-256 hasher
const sha256Hasher = crypto.createHmac("sha256", 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 😃!";

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

// create a sha-256 hasher
const sha256Hasher = crypto.createHmac("sha256", secret);

// hash the string
const hash = sha256Hasher.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 😃!";

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

// create a sha-256 hasher
const sha256Hasher = crypto.createHmac("sha256", secret);

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

// A unique sha256 hash 😃
console.log(hash); // d22101d5d402ab181a66b71bb950ff2892f6d2a1e436d61c4fb1011e9c49a77a

We have now successfully hashed our string using the sha-256 algorithm ✅.

See the code snippet live in repl.it.

Feel free to share if you found this useful 😃.