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.