JAVASCRIPT

Secure Password Hashing with bcrypt (Node.js)

Learn to securely hash and verify user passwords using the bcrypt library in Node.js, an essential practice for protecting sensitive user data against breaches.

const bcrypt = require('bcrypt');
const saltRounds = 10; // Adjust salt rounds for desired security/performance balance

async function hashPassword(plainPassword) {
    try {
        const hashedPassword = await bcrypt.hash(plainPassword, saltRounds);
        return hashedPassword;
    } catch (error) {
        console.error('Error hashing password:', error);
        throw new Error('Password hashing failed.');
    }
}

async function verifyPassword(plainPassword, hashedPassword) {
    try {
        const isMatch = await bcrypt.compare(plainPassword, hashedPassword);
        return isMatch;
    } catch (error) {
        console.error('Error verifying password:', error);
        throw new Error('Password verification failed.');
    }
}

// Example Usage:
// (async () => {
//     const myPassword = 'mySecretPassword123!';
//     const hashed = await hashPassword(myPassword);
//     console.log('Hashed Password:', hashed);

//     const isCorrect = await verifyPassword(myPassword, hashed);
//     console.log('Password Correct:', isCorrect); // Should be true

//     const isIncorrect = await verifyPassword('wrongPassword', hashed);
//     console.log('Password Incorrect:', isIncorrect); // Should be false
// })();
How it works: This snippet demonstrates how to securely hash and verify passwords using the `bcrypt` library in Node.js. `bcrypt` adds a random salt and performs multiple rounds of hashing, making it computationally expensive to crack, even with rainbow tables. The `saltRounds` variable controls the complexity, balancing security with performance. It's crucial for protecting user credentials against brute-force attacks and database breaches, going beyond simple password policy validation.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs