One of the best ways to store passwords securely is to salt and hash them. Salting and hashing converts a plain password to a unique value that is difficult to reverse. The bcrypt library lets you hash and salt passwords in Node.js with very little effort.
What Is Password Hashing?
Password hashing means passing a plain text password through a hashing algorithm to generate a unique value. Some examples of hashing algorithms are bcrypt, scrypt, and SHA. The downside of hashing is that it is predictable.
Every time you pass the same input to a hashing algorithm, it will generate the same output. A hacker with access to the hashed password can reverse engineer the encryption to get the original password. They may use techniques such as brute-force attacks or rainbow tables. This is where salting comes in.
What Is Password Salting?
Password salting adds a random string (the salt) to a password before hashing it. This way, the hash generated will always be different each time. Even if a hacker obtains the hashed password, it is impractical for them to discover the original password that generated it.
How to Use bcrypt to Hash and Verify a Password
bcrypt is an npm module that simplifies password salting and hashing.
Step 1: Install bcrypt
Using npm:
npm install bcrypt
Using yarn:
yarn add bcrypt
Step 2: Import bcrypt
const bcrypt = require("bcrypt")
Step 3: Generate a Salt
To generate the salt, call the bcrypt.genSalt() method. This method accepts an integer value which is the cost factor that determines the time taken to hash a password. The higher the cost factor, the more time the algorithm takes and the more difficult it is to reverse the hash using brute force. A good value should be high enough to secure the password but also low enough not to slow down the process. It commonly ranges between 5 and 15. In this tutorial, we will use 10.
bcrypt.genSalt(10, (err, salt) => {
// use salt to hash password
})
Step 4: Hash the Password
Pass the plain password and the generated salt to the hash() method:
bcrypt.genSalt(10, (err, salt) => {
bcrypt.hash(plaintextPassword, salt, function(err, hash) {
// Store hash in the database
});
})
