Difficulty: Intermediate
Why is bcrypt a better choice than SHA-256 for storing user passwords? Explain the salt and the cost factor.
SHA-256 is a general purpose hash built to be fast, so an attacker who steals your database can try billions of password guesses per second on a single GPU. Bcrypt is a password hashing function that is deliberately slow, has a tunable cost factor you raise as hardware gets faster, and generates and stores a unique random salt for every hash automatically. Together these make offline brute force and precomputed tables far more expensive.
Hash functions like SHA-256 are designed for integrity checks, signatures and file checksums, where speed is a feature. For passwords, speed helps the attacker. Once a database leaks, the attacker is not limited by your login rate limiter; they crack hashes offline on their own hardware. Human chosen passwords come from a small, predictable space (names, dictionary words, Password@123), so a fast hash lets them test a huge wordlist with rules in minutes. A plain unsalted SHA-256 is also vulnerable to rainbow tables, and identical passwords produce identical hashes, which leaks who shares a password.
Bcrypt is built on the Blowfish cipher with an expensive key setup called EksBlowfish. The cost (also called work factor or log rounds) is an exponent: cost 12 means 2^12 rounds of key expansion. Each +1 doubles the time to compute one hash, for you and for the attacker.
10 is the common library default; 12 is a typical modern choice.A bcrypt hash looks like $2b$12$ followed by 53 characters: a 22 character salt (128 bits) and a 31 character hash. Because the salt is random per hash and embedded in the output, two users with the password Swiggy@2024 get completely different hashes, and rainbow tables are useless. You never store the salt in a separate column; bcrypt.compare reads it back out of the stored string.
| Algorithm | Tunable cost | Memory hard | Notes |
|---|---|---|---|
| SHA-256 / MD5 | No | No | Never for passwords |
| PBKDF2-HMAC-SHA256 | Iterations | No | FIPS friendly; OWASP suggests 600,000 iterations |
| bcrypt | Cost exponent | Slightly | Mature, everywhere; 72 byte input limit |
| Argon2id | Time, memory, parallelism | Yes | OWASP's first recommendation for new systems |
Argon2id is now the preferred choice for new projects because it is memory hard, which hurts GPU and ASIC attackers more. Bcrypt with cost 10 or higher is still considered acceptable and is what most existing systems use.
sha256(salt + password) in a loop yourself. Use a vetted library.bcrypt.hash, not hashSync) so hashing does not block the event loop.compare function, not string equality on hashes.import bcrypt from 'bcrypt';
const COST = 12; // each +1 doubles hashing time
export async function hashPassword(plain) {
// genSalt + hash in one step; salt is embedded in the result
return bcrypt.hash(plain, COST);
}
export async function verifyPassword(plain, storedHash) {
const ok = await bcrypt.compare(plain, storedHash);
// Upgrade old hashes transparently after a successful login
if (ok && bcrypt.getRounds(storedHash) < COST) {
const upgraded = await bcrypt.hash(plain, COST);
// await db.user.update({ passwordHash: upgraded })
}
return ok;
}
const h = await hashPassword('Swiggy@2024');
console.log(h);
console.log(await verifyPassword('Swiggy@2024', h));
The async API keeps the event loop free. The rehash on login lets you raise the cost over the years without forcing password resets.
from argon2 import PasswordHasher
# Defaults in argon2-cffi follow RFC 9106 recommendations
ph = PasswordHasher()
stored = ph.hash("correct-horse-battery-staple")
print(stored[:30], "...")
try:
ph.verify(stored, "correct-horse-battery-staple")
if ph.check_needs_rehash(stored):
stored = ph.hash("correct-horse-battery-staple")
print("login ok")
except Exception:
print("bad password")
Argon2id adds a memory cost on top of the time cost, which makes GPU cracking much less efficient. The same rehash-on-login pattern applies.
Bcrypt, Salt, Cost Factor, Rainbow Tables, Argon2id