JAVASCRIPT
Hash Passwords Securely with Bcrypt
Learn to securely hash and verify user passwords in your Node.js applications using the robust bcrypt library to protect against credential breaches.
const bcrypt = require('bcrypt');
const plainTextPassword = 'mySecretPassword123';
const saltRounds = 10; // A higher value increases security but takes more time
async function hashPassword(password) {
try {
const hashedPassword = await bcrypt.hash(password, saltRounds);
console.log('Hashed Password:', hashedPassword);
return hashedPassword;
} catch (err) {
console.error('Error hashing password:', err);
throw err;
}
}
async function comparePassword(plainPassword, hashedPassword) {
try {
const match = await bcrypt.compare(plainPassword, hashedPassword);
console.log('Password match:', match);
return match;
} catch (err) {
console.error('Error comparing password:', err);
throw err;
}
}
// Example Usage:
(async () => {
const hashed = await hashPassword(plainTextPassword);
await comparePassword(plainTextPassword, hashed); // Should be true
await comparePassword('wrongPassword', hashed); // Should be false
})();
How it works: This snippet demonstrates secure password handling using the `bcrypt` library, which is essential for protecting user credentials. Instead of storing plain-text passwords, `bcrypt` hashes them, making them irreversible. It incorporates a salt, which is a random string added to the password before hashing, preventing 'rainbow table' attacks and ensuring that identical passwords result in different hashes. The `saltRounds` parameter determines the computational cost (and thus security strength) of the hashing process; a higher number means more time to hash and crack. The `compare` function safely verifies a plain-text password against a stored hash without ever exposing the original password.