JAVASCRIPT

Secure Password Hashing using bcrypt in Node.js

Learn to securely hash and verify user passwords in Node.js applications using the bcrypt library, protecting sensitive credentials from brute-force attacks and database breaches.

const bcrypt = require('bcrypt');
const saltRounds = 10; // A cost factor. Higher means more secure, but slower.

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

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

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

  console.log('Hashing password...');
  const hash = await hashPassword(userPassword);
  console.log('Hashed Password:', hash);

  console.log('
Comparing correct password...');
  const isMatchCorrect = await comparePassword(userPassword, hash);
  console.log('Matches (Correct Password):', isMatchCorrect);

  console.log('
Comparing incorrect password...');
  const isMatchIncorrect = await comparePassword('wrongPassword', hash);
  console.log('Matches (Incorrect Password):', isMatchIncorrect);
}

main();
How it works: Storing passwords in plain text is a critical security vulnerability. This snippet demonstrates how to use the `bcrypt` library to securely hash user passwords. `bcrypt` adds a random 'salt' to each password before hashing and performs multiple rounds of computation, making it computationally intensive to crack even if a database is breached. The `hashPassword` function takes a plain text password and returns its hash, while `comparePassword` verifies if a given plain text password matches a stored hash without revealing the original password.

Need help integrating this into your project?

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

Hire DigitalCodeLabs