JAVASCRIPT
Implement Secure Password Hashing with Bcrypt
Learn how to securely hash user passwords using the bcrypt library in Node.js to protect against brute-force and rainbow table attacks, a critical security measure.
const bcrypt = require('bcrypt');
const saltRounds = 10; // Recommended value, determines the complexity of hashing
async function hashPassword(plainPassword) {
try {
const hashedPassword = await bcrypt.hash(plainPassword, saltRounds);
return hashedPassword;
} catch (error) {
console.error('Error hashing password:', error);
throw error;
}
}
async function comparePassword(plainPassword, hashedPassword) {
try {
const isMatch = await bcrypt.compare(plainPassword, hashedPassword);
return isMatch;
} catch (error) {
console.error('Error comparing password:', error);
throw error;
}
}
// Example Usage:
// (async () => {
// const userPassword = 'mySecurePassword123!';
// const hashed = await hashPassword(userPassword);
// console.log('Hashed Password:', hashed);
// const isValid = await comparePassword(userPassword, hashed);
// console.log('Password matches:', isValid); // true
// const isInvalid = await comparePassword('wrongPassword', hashed);
// console.log('Password matches (wrong):', isInvalid); // false
// })();
How it works: This snippet demonstrates how to use the `bcrypt` library to securely hash and verify user passwords in a Node.js application. `bcrypt` is a strong, adaptive hashing function designed to be slow and resistant to brute-force attacks. `saltRounds` determines the computational cost; higher values are more secure but slower. Passwords should always be hashed before storage and verified using `bcrypt.compare` to prevent storing plain-text passwords, a critical security vulnerability.