How to create SHA256 password hash using NodeJS? Code Examples

Total
0
Shares

In order to create SHA256 password hash using NodeJS, we can use node:crypto module. It has a createHmac() function which accepts the algorithm and secret key as parameters. Then we can chain it with update() function which takes the string to hash.

Code Example

let crypto;
try {
  crypto = require('node:crypto');

  const secret = "#&Yghs&$^#GFJE*475738";

  const hash = crypto
    .createHmac("sha256", secret)
    .update("Tony Stark is Ironman")
    .digest("hex");

  console.log(hash);

} catch (err) {
  console.log('crypto support is disabled!');
}

The output is –

c87cbbcfc699498cfe52c7b86dc69e3302fde8edaeb81ac12c7294b7561a05ae

Live Demo

Open Live Demo

In this example we included the node crypto module node:crypto and stored it in crypto variable. We have defined a secret key because the hashing function use this key to create hash. Keep this key as strong as possible and save it in environment variable. As a good security practice periodically change this key.

You can also see that we are first checking if node:crypto module is available with the node package or not using try/catch block. This is because some node versions do not come shipped with this module. In that case you can install it using npm.

SHA256 is a strong crypto protocol which cannot be decoded. It means the output in the above code can’t be converted back to our string “Tony Stark is Ironman“.

Use Cases of SHA256

There are many use cases of SHA256 hash like –

  • You can use it to store users’ passwords in database.
  • Can use it as object ids for uniqueness.
  • Same strings for a secret key will always generate the same hash. So it is used to check strings equality.

Using SHA256 for Passwords

I said that SHA256 hash can’t be decoded back to string then how could you check for the correctness of the password? For example, when a user registers on a website they provide a password in plain text. That password is converted by backend to a SHA256 hash and stored in database. But server do not keep the plain text. And, hash can’t be converted to plain text.

Now if a user signs out and logs back in with a plain text password then how server matches it with hashes in database? Well, that plain text password is converted to SHA256 again and this generated hash is matched with the hash in database. If it matches then user logs in successfully otherwise authentication error.