Nodejs: Hash a Password with bcrypt

bcrypt is a popular JavaScript library generally used to hash plain text passwords.

node-bcrypt

Nodejs: Hash a Password with bcrypt

bcrypt is a popular JavaScript library generally used to hash plain text passwords.

Whenever you store passwords in a database you should never save them in plain text. The easy way to hide the text from view is to hash the password, so a password like “ABc321” becomes:


$2b$10$4g.gcZiGml3j1yVSywp7QevSRBS2.veSSmnLWOintVpRzS3SXTej2

The next time the user enters their password you just need to hash it again and see if you get the same string as the previous hash.

Hashing can be done easily using a node module called bcrypt. bcrypt is popular and has about 500,000 downloads weekly from npmjs.com.

First install the library using npm:


npm i bcrypt

Then include it in the file where you will be using it:


const bcrypt = require('bcrypt')

Using bcrypt is easy:


const hashedPassword = bcrypt.hash(plainPassword, 10)

The second parameter is the number of salt rounds to use, the higher the number the more secure the hash. Using too high a number will make the hash generation slow, the default of 10 is a good number and reasonably fast.

You can also mark your function as async and await bcrypt:


const hashedPassword = await bcrypt.hash(plainPassword, 10)

To save time, bcrypt provides a function to compare plain and hashed strings:


bcrypt.compare(plainPassword, hashedPassword, function(err, result) {
// result will be true or false
});

Documentation for bcrypt

You can find the documentation for bcrypt at https://github.com/kelektiv/node.bcrypt.js

If you want to learn more how crypt works, there is a wikipedia entry explaining this at https://en.wikipedia.org/wiki/Bcrypt