Using Bcrypt to Hash and Verify Passwords

Bcrypt is a hashing function based on the Blowfish cipher that allows for the protection of sensitive information, such as passwords. It was designed in 1999 and it still used today around the world.

To use this in a Node application we can use the npm package called bcrypt.js. After requiring the library we can begin to hash data:

const bcrypt = require('bcryptjs');

const hashPassword = async () => {
  const hash = await bcrypt.hash('password', 10);


// Output: $2a$10$d5Dv4SpUfioaE3IcIwC11.cXO5.xw7joBW6UJzW5KSRR1t1LMuAsm

Two arguments are provided to bcrypt’s hash method: the string to hash and the amount of key expansion rounds to use. In our case we are hashing ‘password’ are the amount of rounds run will be 2^10.

A key point to note is that our password is not being encrypted. If it were being encrypted we would have a key available to reverse the encryption and display the plaintext version. With a hash it is impossible to reverse and display a plaintext value.

In order to verify that a password matches the hash, we use bcrypt’s compare method. This method will take two arguments: the string you want to compare to the hash, and the hash itself.

const bcrypt = require('bcryptjs');

const hashAndComparePassword = async () => {
  const hash = await bcrypt.hash('password', 10);
  let isMatch = await bcrypt.compare('password123', hash);
  isMatch = await bcrypt.compare('password', hash);


// Output: false
// Output: true

So if the hash cannot be reversed how does bcrypt know ‘password’ is valid and ‘password123’ is not? During the hash process Bcrypt adds a plaintext salt to each password. When Bcrypt compares a password to a given hash, it uses the salt from the provided hash to actually hash the given password and then compares the two hashes.

Leave a Reply

Your email address will not be published. Required fields are marked *

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