JAVASCRIPT

Robust Password Hashing with bcrypt in Node.js

Secure user passwords by implementing strong, one-way hashing with the bcrypt library in Node.js, preventing plaintext storage and rainbow table attacks.

const bcrypt = require('bcrypt');

const hashPassword = async (password) => {
  const saltRounds = 10; // The cost factor, higher is slower and more secure
  try {
    const hashedPassword = await bcrypt.hash(password, saltRounds);
    console.log('Hashed Password:', hashedPassword);
    return hashedPassword;
  } catch (error) {
    console.error('Error hashing password:', error);
    throw error;
  }
};

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

// Example Usage:
(async () => {
  const userPassword = 'mySecretPassword123';
  const storedHash = await hashPassword(userPassword);

  // When a user tries to log in
  const loginAttemptPassword = 'mySecretPassword123';
  await comparePassword(loginAttemptPassword, storedHash);

  const wrongPassword = 'wrongPassword';
  await comparePassword(wrongPassword, storedHash);
})();
How it works: This snippet demonstrates how to securely hash and verify user passwords using the `bcrypt` library in Node.js. `bcrypt` is recommended because it's designed to be slow, making brute-force attacks computationally intensive, and it automatically handles salting, which prevents rainbow table attacks by adding a random string to each password before hashing. The `saltRounds` parameter determines the computational cost; higher values increase security but also processing time. `bcrypt.hash()` generates a one-way hash, and `bcrypt.compare()` safely verifies a plaintext password against 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