JAVASCRIPT
Securely Hash Passwords Using Bcrypt in Node.js
Learn to securely hash and verify user passwords using the robust bcrypt library in a Node.js application to protect against data breaches and brute-force attacks.
const bcrypt = require('bcrypt');
const saltRounds = 10; // The cost factor, higher is slower but more secure
async function hashPassword(plainPassword) {
try {
const hashedPassword = await bcrypt.hash(plainPassword, saltRounds);
console.log('Hashed Password:', hashedPassword);
return hashedPassword;
} catch (error) {
console.error('Error hashing password:', error);
throw error;
}
}
async function comparePassword(plainPassword, hashedPassword) {
try {
const match = await bcrypt.compare(plainPassword, hashedPassword);
console.log('Password Match:', match);
return match;
} catch (error) {
console.error('Error comparing password:', error);
throw error;
}
}
// Example Usage:
(async () => {
const userPassword = 'mySecretPassword123';
// 1. Hash the password
const hashed = await hashPassword(userPassword);
// 2. Later, when a user tries to log in, compare the entered password with the stored hash
const enteredPasswordCorrect = 'mySecretPassword123';
const enteredPasswordWrong = 'wrongPassword';
console.log('
Comparing correct password:');
await comparePassword(enteredPasswordCorrect, hashed); // Should be true
console.log('
Comparing incorrect password:');
await comparePassword(enteredPasswordWrong, hashed); // Should be false
})();
How it works: This snippet demonstrates the secure way to handle user passwords in Node.js using the `bcrypt` library. `bcrypt` is a password-hashing function designed to be computationally intensive, making brute-force attacks difficult even with powerful hardware. It automatically generates a unique salt for each password and incorporates it into the hash, preventing rainbow table attacks. The `saltRounds` parameter controls the work factor, allowing you to balance security and performance.