JAVASCRIPT

Securely Hashing Passwords in Node.js with bcrypt

Learn to securely store user passwords in Node.js applications by using the `bcrypt` library for strong, salted hashing, protecting against brute-force attacks and rainbow tables.

const bcrypt = require('bcrypt');
const saltRounds = 10; // A good balance between security and performance

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

async function comparePassword(plainPassword, hashedPassword) {
    try {
        const isMatch = await bcrypt.compare(plainPassword, hashedPassword);
        return isMatch;
    } catch (error) {
        console.error('Error comparing password:', error);
        throw error;
    }
}

// Example usage:
async function main() {
    const userPassword = 'mySuperSecurePassword123!';

    // Hash the password
    const hashed = await hashPassword(userPassword);
    console.log('Hashed Password:', hashed);

    // Verify a correct password
    const correctMatch = await comparePassword(userPassword, hashed);
    console.log('Password matches (correct):', correctMatch); // true

    // Verify an incorrect password
    const incorrectMatch = await comparePassword('wrongPassword', hashed);
    console.log('Password matches (incorrect):', incorrectMatch); // false
}

main();
How it works: This Node.js snippet demonstrates the secure practice of hashing user passwords using the `bcrypt` library. The `hashPassword` function generates a cryptographically strong salt and then hashes the plain-text password with a specified number of `saltRounds`, making it extremely difficult to reverse-engineer. The `comparePassword` function safely verifies a provided plain-text password against a stored hash without revealing the original. This approach protects against common attacks like rainbow table lookups and brute-force attempts by ensuring passwords are never stored in plain text.

Need help integrating this into your project?

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

Hire DigitalCodeLabs