JAVASCRIPT
Securely Hash and Verify Passwords with Bcrypt
Protect user credentials by implementing strong, one-way password hashing using the bcrypt library for secure storage and verification in Node.js applications.
// Install: npm install bcrypt
const bcrypt = require('bcrypt');
const saltRounds = 10; // Recommended value, balances security and performance
async function hashPassword(plainTextPassword) {
try {
const hash = await bcrypt.hash(plainTextPassword, saltRounds);
return hash;
} catch (error) {
console.error("Error hashing password:", error);
throw new Error("Failed to hash password");
}
}
async function comparePassword(plainTextPassword, hashedPassword) {
try {
const match = await bcrypt.compare(plainTextPassword, hashedPassword);
return match; // true if passwords match, false otherwise
} catch (error) {
console.error("Error comparing password:", error);
throw new Error("Failed to compare password");
}
}
// Example usage:
/*
async function example() {
const userPassword = "MySecretPassword123";
const hashedPassword = await hashPassword(userPassword);
console.log("Hashed Password:", hashedPassword);
const isMatch = await comparePassword(userPassword, hashedPassword);
console.log("Password matches:", isMatch); // Should be true
const wrongPasswordMatch = await comparePassword("WrongPassword", hashedPassword);
console.log("Wrong password matches:", wrongPasswordMatch); // Should be false
}
example();
*/
How it works: This snippet illustrates how to securely hash and verify user passwords using the `bcrypt` library in Node.js. Instead of storing plain text passwords, which is highly insecure, `bcrypt` generates a one-way hash that includes a random salt, making it extremely difficult to reverse-engineer even if the database is compromised. `saltRounds` determines the computational cost, balancing security with server load. The `hashPassword` function hashes a new password, while `comparePassword` safely verifies a user-provided password against its stored hash without exposing the original password.