JAVASCRIPT
Securely Hash User Passwords with Bcrypt in Node.js
Learn to implement robust password hashing using the `bcrypt` library in Node.js, ensuring secure storage and comparison of user credentials against common attacks.
const bcrypt = require('bcrypt');
const saltRounds = 10; // A higher value means more secure but slower 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 match = await bcrypt.compare(plainPassword, hashedPassword);
return match;
} catch (error) {
console.error('Error comparing password:', error);
throw error;
}
}
// Example Usage:
(async () => {
const userPassword = 'mySecretPassword123!';
const storedHash = await hashPassword(userPassword);
console.log('Hashed Password:', storedHash);
const isMatch = await comparePassword(userPassword, storedHash);
console.log('Password Match (Correct):', isMatch); // Should be true
const isMismatch = await comparePassword('wrongPassword', storedHash);
console.log('Password Match (Incorrect):', isMismatch); // Should be false
})();
How it works: This code snippet illustrates how to securely hash and verify user passwords using the `bcrypt` library in Node.js. `bcrypt` is a recommended algorithm because it is slow by design, making brute-force attacks computationally expensive. It automatically generates a unique salt for each password, preventing rainbow table attacks. The `saltRounds` parameter controls the computational cost, balancing security with performance.