According to Wikipedia “bcrypt is a password hashing function designed by Niels Provos and David Mazières, based on the Blowfish cipher.
In real life applications with User authentication functionality, it is not practical to store user password as the original string in the database but it is good practice to hash the password and then store them into the database.
Bcrypt package for Node JS helps developers to hash user password.
Install via NPM
npm install bcrypt
Cryptography terms
Before we use it, let’s first have a look at some terms.
Salt: A salt is a random data that is used as an additional input to a one-way function that hashes data.
Salt Rounds: This is the cost factor that indicates the amount of time needed to calculate a single bcrypt hash. Higher the salt rounds, the more hashing rounds are done, hence the time and difficulty is increased while brute-forcing. For example, a cost factor of n means that the calculation will be done 2^n times.
Implementation
const bcrypt = require('bcrypt');
const saltRounds = 10;
const yourPassword = "someRandomPasswordHere";
So, there are two ways to hash a password:
Technique 1 (generate a salt and hash on separate function calls):
bcrypt.genSalt(saltRounds, function(err, salt) {
bcrypt.hash(myPlaintextPassword, salt, function(err, hash) {
// Store hash in your password DB.
});
});
Technique 2 (auto-gen a salt and hash):
bcrypt.hash(myPlaintextPassword, saltRounds, function(err, hash) {
// Store hash in your password DB.
});
Note that both techniques achieve the same end-result.
To check a password:
// Load hash from your password DB.
bcrypt.compare(myPlaintextPassword, hash, function(err, result) {
// result == true
});
bcrypt.compare(someOtherPlaintextPassword, hash, function(err, result) {
// result == false
});
Both the ways mentioned above can also be achieved with promises, these methods (hash & compare) will return a Promise when a callback is not defined.
Bcrypt also provides methods like genSaltSync, HashSync and CompareSync to perform synchronously. However, aysnc methods are preferred because of the fact that hashing done by bcyrpt is CPU intensive, so the sync methods will block event loop and our application will not serve any other request until the sync methods are completed executed.