How to use Bcrypt module to Hash and save passwords in the node.js

How to use Bcrypt module to Hash and save passwords in the node.js

Posted by Rahul Dhokia | July 5, 2016

Using Bcrypt is the perfect way to save passwords in the database regardless of whatever language your backend is using – PHP, Ruby, Python, Node.js, etc.
So, lets see  how do we integrate Bcrypt  in Node.js
Thankfully we have a bcrypt module available to use. It’s super easy to use, lets see how.
First of all install it via NPM.

1
$ npm install bcrypt --save

The module provides us 2 ways to bcrypt the password.

1) Sync Usage

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
// Load the bcrypt module
var bcrypt = require('bcrypt');
// Generate a salt
var salt = bcrypt.genSaltSync(10);
// Hash the password with the salt
var hash = bcrypt.hashSync("password", salt);</code>
 
Now we can save hash variable in our database. During authentication you need to check the incoming password string against the hash.
 
<code>var hash = YOUR SAVED PASSWORD IN DB;
bcrypt.compareSync("password", hash); // true
bcrypt.compareSync("not my password", hash); // false </code>
 
"password" is the correct one (sent via login form or some other method by the user) hence compareSync returns true while in the second case, when the password is incorrect, it returns false.
<h3>2) Async Usage</h3>
<code> var bcrypt = require('bcrypt');
var salt = bcrypt.genSaltSync(10);
bcrypt.hash('password', salt , function(err, hash) {
// Store hash in your password DB.
});

And this is how we can compare the hash saved in DB with the user password –

1
2
3
4
// Load password hash from DB
bcrypt.compare("password", hash, function(err, res) {
// res === true
});
1
2
3
bcrypt.compare("not my password", hash, function(err, res) {
// res === false
});

If you’re wondering what the 10 (that’s used for hashing) is, then that’s the work factor or the number of rounds the data is processed for. More rounds leads to more secured hash but slower/expensive process.

Add a comment

*Please complete all fields correctly

Related Blogs