JAVASCRIPT

Secure Password Hashing and Verification with Node.js and bcrypt

Implement robust password security in Node.js applications by hashing and verifying user passwords using the industry-standard bcrypt library.

const bcrypt = require('bcrypt');

// In a real application, you would typically configure your salt rounds
const saltRounds = 10; // Recommended value, higher is more secure but slower

/**
 * Hashes a plain-text password using bcrypt.
 * @param {string} password - The plain-text password to hash.
 * @returns {Promise<string>} - A promise that resolves with the hashed password.
 */
async function hashPassword(password) {
    try {
        const hash = await bcrypt.hash(password, saltRounds);
        return hash;
    } catch (error)
    {
        console.error("Error hashing password:", error);
        throw error;
    }
}

/**
 * Compares a plain-text password with a hashed password.
 * @param {string} password - The plain-text password to compare.
 * @param {string} hash - The hashed password stored in the database.
 * @returns {Promise<boolean>} - A promise that resolves with true if passwords match, false otherwise.
 */
async function comparePassword(password, hash) {
    try {
        const match = await bcrypt.compare(password, hash);
        return match;
    } catch (error) {
        console.error("Error comparing password:", error);
        throw error;
    }
}

// Example Usage:
async function testPasswordSecurity() {
    const userPassword = 'mySecurePassword123!';

    // 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 user login)
    const isMatchCorrect = await comparePassword(userPassword, hashedPassword);
    console.log('Password match (correct):', isMatchCorrect); // Expected: true

    const isMatchIncorrect = await comparePassword('wrongPassword', hashedPassword);
    console.log('Password match (incorrect):', isMatchIncorrect); // Expected: false
}

// Execute the example
// testPasswordSecurity(); // Uncomment to run example
How it works: This Node.js snippet demonstrates how to securely store and verify user passwords using the `bcrypt` library. Passwords are never stored in plain text. Instead, `hashPassword` generates a cryptographically strong hash by applying a one-way function and a unique salt for each password, making it extremely difficult to reverse engineer. The `comparePassword` function then safely verifies a plain-text input against a stored hash without ever revealing the original password, crucial for user authentication.

Need help integrating this into your project?

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

Hire DigitalCodeLabs