Lesson 27 +10 XP

Password Hashing with bcrypt

Never Store Plaintext Passwords

Storing unencrypted user passwords in databases is a severe security vulnerability. Passwords must be hashed using a slow, salted, cryptographically secure hash function like bcrypt.

How Salted Hashing Works

  • Salt: A random string added to the password before hashing to prevent rainbow table pre-computation attacks.
  • Cost Factor (Salt Rounds): Controls how much time is required to calculate a hash (e.g. 10 to 12 rounds is standard).
const bcrypt = require("bcrypt");

// Hashing password during user registration
async function registerUser(plainPassword) {
  const saltRounds = 10;
  const passwordHash = await bcrypt.hash(plainPassword, saltRounds);
  console.log("Hashed Password:", passwordHash);
  return passwordHash;
}

// Verifying password during user login
async function loginUser(enteredPassword, storedHash) {
  const isMatch = await bcrypt.compare(enteredPassword, storedHash);
  if (!isMatch) {
    throw new Error("Invalid email or password");
  }
  console.log("Authentication successful!");
  return true;
}

TL;DR

  • Use bcrypt.hash(password, saltRounds) before saving users.
  • Use bcrypt.compare(enteredPassword, storedHash) to verify credentials.
  • Salt rounds = 10 to 12 balances CPU load and security.