JAVASCRIPT

Secure Password Hashing and Verification with bcrypt.js

Implement robust password security in Node.js applications by hashing and verifying user passwords using the bcrypt.js library, protecting against brute-force and rainbow table attacks.

const bcrypt = require('bcrypt');

const saltRounds = 10; // The cost factor, higher means more secure but slower

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

async function verifyPassword(plainPassword, hashedPassword) {
  try {
    const match = await bcrypt.compare(plainPassword, hashedPassword);
    console.log('Password Match:', match);
    return match;
  } catch (err) {
    console.error('Error comparing passwords:', err);
    throw err;
  }
}

// --- Usage Example ---
async function main() {
  const userPassword = 'mySecurePassword123!';

  // 1. Hash the password (e.g., during user registration)
  const hashedPassword = await hashPassword(userPassword);

  // 2. Verify the password (e.g., during user login)
  if (hashedPassword) {
    console.log('
--- Verification Attempt 1 (Correct) ---');
    const isMatch1 = await verifyPassword(userPassword, hashedPassword);
    console.log('Verification Result:', isMatch1 ? 'Success!' : 'Failed!');

    console.log('
--- Verification Attempt 2 (Incorrect) ---');
    const isMatch2 = await verifyPassword('wrongpassword', hashedPassword);
    console.log('Verification Result:', isMatch2 ? 'Success!' : 'Failed!');
  }
}

main();
How it works: This Node.js snippet demonstrates the critical process of securely hashing and verifying user passwords using the `bcrypt.js` library. `bcrypt` is a widely recommended hashing algorithm because it is computationally intensive, making brute-force attacks difficult and slow. The `saltRounds` parameter controls the computational cost. The `hashPassword` function generates a unique hash for a given plain password, and `verifyPassword` safely compares a plain password against a stored hash without revealing the original password, protecting against data breaches and rainbow table attacks.

Need help integrating this into your project?

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

Hire DigitalCodeLabs