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.

$ npm install bcrypt --save

The module provides us 2 ways to bcrypt the password.

1) Sync Usage

// 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 –

// Load password hash from DB
bcrypt.compare("password", hash, function(err, res) {
// res === true
});
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

Posted by Rukmi Patel | December 2, 2019
iTreeni Technolabs Outshines at GoodFirms by Providing End-To-End Business Solutions
Empowering clients' business by leveraging technology-enabled solutions endows iTreeni Technolabs to tap into the list of top web development companies in Australia at GoodFirms. View iTreeni Technolabs' GoodFirms' profile to...
MEAN-Vs-Full-stack
Posted by Rukmi Patel | April 9, 2019
Comparing Full Stack V/S MEAN Stack approach
The web and mobile app development services have stepped up to next level in last 5 years. Web and apps are all built utilizing a ‘stack’ of various technologies like...
Posted by Rukmi Patel | September 6, 2018
Headless Drupal or DeCoupled Drupal
Now a days, front-end technologies like Angular, React.js, Backbone.js etc have started attracting audience because of its advantages over traditional rendering approach. Server side frameworks like Laravel, Node.js have already...