Day 83

bcrypt & Password Hashing

11 min
JavaScript 100 Days

Passwords KABHI plain text mein store mat karo! bcrypt ek strong hashing algorithm hai jo passwords ko securely store karta hai. Salt add karta hai taake same passwords bhi different hashes mein convert hon.

bcrypt Hashing

Passwords hash aur verify karo.

bcrypt.js
javascript
const bcrypt = require("bcrypt");

// Hash banao (register par)
async function hashPassword(plainPassword) {
  const saltRounds = 12; // higher = more secure but slower
  const hashed = await bcrypt.hash(plainPassword, saltRounds);
  console.log("Hash:", hashed);
  // $2b$12$... ← stored in database
  return hashed;
}

// Verify karo (login par)
async function checkPassword(plainPassword, hashedPassword) {
  const isMatch = await bcrypt.compare(plainPassword, hashedPassword);
  return isMatch;
}

// Example
async function demo() {
  const password = "MySecurePass123!";
  
  const hash = await hashPassword(password);
  
  console.log(await checkPassword("MySecurePass123!", hash)); // true
  console.log(await checkPassword("wrongpassword", hash));    // false
  console.log(await checkPassword("MySecurePass123!", hash)); // true again
  // Same password, same hash → true (bcrypt handles this internally)
}

🎯 Practice Challenge

Password change endpoint banao — old password verify karo, new password hash karo, update karo. Strength check add karo.