How to hash and verify passwords in Node.js using bcrypt
If you have to manage user passwords, you need to make sure they're secure. The bcrypt library will make this process easier for you.
One of the best ways to store passwords securely is to salt and hash them. Salt and hash convert a simple password into a unique value that is difficult to reverse. The bcrypt library allows you to hash and salt passwords in Node.js with as little effort as possible.
What is password hash?
Hashing a password means passing a password in plain text through a hash algorithm to generate a unique value. This value is called a hash. Some examples of hash algorithms are bcrypt, scrypt, and SHA.
One of the main properties of a good hash algorithm is that it produces the same output for the same input. This predictability creates a vulnerability that makes the hash vulnerable. Hackers can pre-compute hash values for many commonly used inputs, and then compare them with the hashes in the target value. You can mitigate this vulnerability by using a salt.
What is Salt Password?
Password salt adds a random string to the password before hashing it. This way, every hash generation is always different. Even if a hacker obtains a hashed password, it takes considerable time for them to discover the original password that generated it.
How to use Bcrypt to hash and verify passwords
bcrypt is an npm module that simplifies the way you hash passwords in Node.js. To use it, follow the steps below:
Step 1: Install Bcrypt
Install bcrypt by running the following terminal commands.
Using npm:
npm install bcrypt
Using yarn:
yarn add bcrypt
Step 2: Enter Bcrypt
At the top of the JavaScript file, enter bcrypt.
const bcrypt = require("bcrypt")
Step 3: Create Salt
Call bcrypt.genSalt() to generate a salt. This method accepts an integer value as the cost factor that determines the time it takes to hash the password. The higher the cost factor, the longer the algorithm takes and the harder it is to reverse the encrypted password.
An excellent value that is high enough to protect the password but also low enough to slow down the process. It usually ranges from 5 to 15. The example in the article uses 10.
bcrypt.genSalt(10, (err, salt) => { // use salt to hash password })
Step 4: Hash Password
In the bcrypt.genSalt function, pass the generated simple password and salt to the bcrypt.hash() function to hash the password.
bcrypt.genSalt(10, (err, salt) => { bcrypt.hash(plaintextPassword, salt, function(err, hash) { // Store hash in the database }); })
After generating the hash, store it in the database. You will use it to verify a password and authenticate the user trying to log in.
bcrypt.hash(plaintextPassword, 10, function(err, hash) { // store hash in the database });
Step 5: Compare passwords using bcrypt
To authenticate users, you need to compare the password they provide with the password in the database using the bcrypt.compare() function. This function accepts the plain text password and hash that you have stored, along with a callback function. This callback function provides an object containing any errors that occurred and the overall result from the comparison. If the password matches the hash, the result is true.
bcrypt.compare(plaintextPassword, hash, function(err, result) { if (result) { // password is valid } });
Use Async/Await
You can encrypt passwords in Node.js with Bcrypt using async/await as follows:
async function hashPassword(plaintextPassword) { const hash = await bcrypt.hash(plaintextPassword, 10); // Contains hash in database } // compare passwords async function comparePassword(plaintextPassword, hash) { const result = await bcrypt.compare(plaintextPassword, hash); return result; }
Use Promises
The bcrypt library also supports using promises. For example, here is a password hash function using the then.catch block.
function hashPassword(plaintextPassword) { bcrypt.hash(plaintextPassword, 10) .then(hash => { // Store hash in the database }) .catch(err => { console.log(err) }) }
Likewise, this function compares the plain password from the user with the password hashed with the promise.
function comparePassword(plaintextPassword, hash) { bcrypt.compare(plaintextPassword, hash) .then(result => { return result }) .catch(err => { console.log(err) }) }
You can use the Bcrypt library to hash and verify passwords in Node.js. Password hashing reduces the possibility of cybercriminals accessing simple passwords and using them to access sensitive data or services.
Salting your hashed passwords makes them even more secure. In addition to hashing, always validate password strength as an added security measure.
You should read it
- Check the security of the password
- Schema validation in Node.js using Joi
- 10 things not to do when running Node.js application
- Dissection attacks Pass the Hash
- Event Loop in Node.js
- What is Node.js?
- Concept of Buffer in Node.js
- 5 best password management apps for iOS
- Use an 8-character Windows NTLM password? Congratulations, your password may be unlocked after only 2.5 hours
- Things to know about event-driven programming in Node.js
- Enhance USB security with USB Flash Security application
- Instructions for installing Node.js
Maybe you are interested
14 great features on Google you may not know yet Continuous push of 1,500 is only one of 10 world records that no one has ever broken of Bruce Why can airplanes fly in the sky? The photo series captured the famous 'ghost' controversy Mysterious ancient coins print 'alien' pictures Parents need to know these things to protect them when chickenpox is coming into season