JAVASCRIPT
Implement Secure Password Hashing with Node.js and Bcrypt
Securely hash and verify user passwords in Node.js applications with the bcrypt library. Protect sensitive user credentials against brute-force and other common attacks.
// First, install bcrypt: npm install bcrypt
const bcrypt = require('bcrypt');
const saltRounds = 10; // Recommended value, higher is more secure but slower
async function hashPassword(plainTextPassword) {
try {
const hashedPassword = await bcrypt.hash(plainTextPassword, saltRounds);
return hashedPassword;
} catch (error) {
console.error("Error hashing password:", error);
throw new Error("Password hashing failed.");
}
}
async function verifyPassword(plainTextPassword, hashedPassword) {
try {
const isMatch = await bcrypt.compare(plainTextPassword, hashedPassword);
return isMatch;
} catch (error) {
console.error("Error comparing password:", error);
return false;
}
}
// --- Example Usage ---
(async () => {
const userPassword = 'MySecretPassword123!';
// 1. Hash the password (e.g., during user registration)
const hashedPassword = await hashPassword(userPassword);
console.log('Hashed Password:', hashedPassword);
// 2. Verify the password (e.g., during login)
const isCorrect = await verifyPassword(userPassword, hashedPassword);
console.log('Is password correct?', isCorrect); // Expected: true
const isIncorrect = await verifyPassword('WrongPassword', hashedPassword);
console.log('Is incorrect password correct?', isIncorrect); // Expected: false
})();
How it works: This Node.js snippet demonstrates secure password handling using the `bcrypt` library. Passwords are never stored in plain text. The `hashPassword` function uses `bcrypt.hash` to generate a secure, one-way hash of the plain-text password, incorporating a salt (random data) and multiple rounds (`saltRounds`) to make brute-force attacks computationally expensive. The `verifyPassword` function uses `bcrypt.compare` to safely check if a given plain-text password matches a stored hash, without needing to re-hash the original password or exposing the original.