🟢 Node.js Intermediate

What is bcrypt and why is it used for passwords?

Answer

bcrypt is a password hashing algorithm designed specifically for storing passwords securely. Unlike general cryptographic hashes (MD5, SHA-256) which are designed to be fast, bcrypt is intentionally slow — making brute-force and rainbow table attacks computationally expensive. It automatically generates and incorporates a random salt (preventing rainbow table attacks) and has a configurable cost factor (work factor) that can be increased over time as hardware gets faster. The bcrypt npm package usage: (1) Hash on registration: const hash = await bcrypt.hash(password, 12); (12 is the salt rounds — higher = slower = more secure); (2) Verify on login: const match = await bcrypt.compare(plaintext, hash); — returns boolean. Never compare password hashes with === (timing attacks). Never store plaintext passwords. Bcrypt truncates at 72 bytes — for longer passwords, consider argon2 (the newer, recommended algorithm) which won the Password Hashing Competition.