In this tutorial, we will dive into password hashing using Bcrypt in Node.js. Our goal is to enhance the security of user passwords by applying a cryptographic hash function. You will learn how to apply a salt to the password hashes to make them even more secure.
You will learn:
- What password hashing and salting is
- How to use Bcrypt for password hashing
- How to use Bcrypt for adding a salt to the password hash
Prerequisites:
- Basic understanding of JavaScript
- Node.js and NPM installed on your machine
- Basic understanding of password security
Hashing is the process of converting plain text into an irreversible set of characters. This is useful for storing passwords in a database as it adds an extra layer of security. If a hacker gained access to your database, they would only see the hashed password, not the original text.
Salting is another layer of security on top of hashing. It involves adding random data to the password before hashing it. This makes each hashed password unique, even if two users have the same password.
Bcrypt is a password hashing function which incorporates salt as part of the hash. This means we can both hash and salt our passwords using Bcrypt.
Install Bcrypt module using npm:
npm install bcrypt
Example 1: Hashing a password
const bcrypt = require('bcrypt');
async function hashPassword(password) {
const saltRounds = 10; // Defines the complexity of the salt
const hashedPassword = await bcrypt.hash(password, saltRounds);
console.log(hashedPassword);
}
hashPassword('myPassword123');
In this example, we first require the Bcrypt module. Then, we create an asynchronous function hashPassword
that takes a password and hashes it with a specified salt round. The salt round defines the complexity of the salt. Higher numbers means more complex salts, but also more processing time. The hashed password is then logged in the console.
Example 2: Comparing a plain text password to a hashed password
const bcrypt = require('bcrypt');
async function comparePasswords(password, hashedPassword) {
const match = await bcrypt.compare(password, hashedPassword);
console.log(match ? 'Passwords match!' : 'Passwords do not match!');
}
comparePasswords('myPassword123', '$2b$10$K4miL7I4h0ThNSBBQDyjeu7l2OBiO7VkzE2pBAvH7s24Eh8m3vz1S');
In this example, we use Bcrypt's compare
function to check if a plain text password matches a hashed password. It returns a boolean indicating whether or not they match.
In this tutorial, you've learned how to hash passwords and add a salt to them using Bcrypt in Node.js. You also learned how to compare a plain text password to a hashed password.
For further learning, consider exploring different salting techniques, or how to integrate this password hashing into a user registration system.
Solutions:
const saltRounds = 10;
to const saltRounds = 5;
const saltRounds = 10;
to const saltRounds = 12;