Bcrypt: Salt & Cost

Difficulty: Intermediate

Question

Why is bcrypt a better choice than SHA-256 for storing user passwords? Explain the salt and the cost factor.

Answer

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.

Why a fast hash is the wrong tool

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.

What the cost factor does

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.

  • Pick a cost so one hash takes roughly 100 to 300 ms on your production servers. Cost 10 is the common library default; 12 is a typical modern choice.
  • The cost is stored inside the hash string, so you can raise it later. On the next successful login, verify with the old cost and silently rehash with the new one.
  • Login becomes slightly slower for a real user, which nobody notices, while the attacker's cracking rate drops by many orders of magnitude.

How the salt is built in

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.

Bcrypt vs other options in 2026

AlgorithmTunable costMemory hardNotes
SHA-256 / MD5NoNoNever for passwords
PBKDF2-HMAC-SHA256IterationsNoFIPS friendly; OWASP suggests 600,000 iterations
bcryptCost exponentSlightlyMature, everywhere; 72 byte input limit
Argon2idTime, memory, parallelismYesOWASP'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.

Gotchas interviewers like to probe

  • 72 byte limit: bcrypt ignores input beyond 72 bytes. Long passphrases or multi-byte UTF-8 characters can hit it. Either cap password length or pre-hash carefully (base64 encode the pre-hash so null bytes do not truncate it).
  • Do not roll your own: never write sha256(salt + password) in a loop yourself. Use a vetted library.
  • Use async APIs in Node.js (bcrypt.hash, not hashSync) so hashing does not block the event loop.
  • Compare safely: use the library's compare function, not string equality on hashes.
Bcrypt hash and verify. The salt and cost travel inside the stored hash, so verification needs only the stored string and the typed password.
  1. User password: Plain text typed at signup or login.
  2. Random 128-bit salt: Generated fresh for every new hash.
  3. EksBlowfish with 2^cost rounds: Deliberately slow key setup.
  4. Stored string $2b$12$...: Version, cost, salt and hash in 60 characters.
  5. compare() on login: Re-derives with the same salt and cost, then compares.

Code examples

Hashing and verifying with bcrypt in Node.js

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.

Argon2id for new projects (Python)

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.

Key points

  • Fast hashes (MD5, SHA-1, SHA-256) are wrong for passwords because attackers crack offline at GPU speed
  • Bcrypt cost is an exponent: cost 12 means 2^12 rounds, and each +1 doubles the work
  • The salt and cost are embedded in the 60 character bcrypt string; no separate salt column
  • Bcrypt only uses the first 72 bytes of input
  • Argon2id is the preferred choice for new systems; bcrypt cost 10+ remains acceptable

Common follow-up questions

  • How would you choose the right cost factor for your servers?
  • How do you migrate an existing database of SHA-256 hashes to bcrypt without forcing resets?
  • What does it mean for Argon2 to be memory hard and why does that matter?
  • What is a pepper and would you add one on top of bcrypt?

Interview tips

  • Lead with the threat model: the database has leaked and the attacker cracks offline, so login rate limits do not help
  • Mention the 72 byte limit and Argon2id; it shows you know the current guidance, not just the textbook answer
  • Explain how you would raise the cost over time with rehash-on-login

Concepts covered

Bcrypt, Salt, Cost Factor, Rainbow Tables, Argon2id

More Web Security (OWASP, JWT, XSS, CSRF) questions