
If an attacker gets a database of plaintext passwords, every account is immediately exposed. If the database contains slow, salted password hashes instead, the attacker must attempt guesses one at a time for each account. That delay is why password hashing is a core backend security control.
This guide explains bcrypt password hashing, salts, cost factors, verification, and safe migration. Read Authentication vs Authorization: What’s the Difference?, How JWT Works Internally, and Sessions vs JWT Tokens: Complete Comparison for the wider identity model. Then continue in the Practical Backend Engineering series or the Security category.
Table of Contents
Open Table of Contents
Hashing Is Not Encryption
Encryption is reversible with a key. Password storage should not need reversal: a service only needs to answer whether a login attempt matches the password chosen earlier. A password hash is a one-way result designed for comparison, not recovery.
Fast general-purpose hashes such as SHA-256 are useful for integrity checks but are a poor primary password store. Attackers can compute them extremely quickly at scale. Password hashing algorithms deliberately make each guess expensive. Bcrypt is a long-standing adaptive password hash; OWASP recommends modern password-hashing schemes such as Argon2id when available and bcrypt for compatible systems that need it.
How bcrypt Works
At registration, the server gives bcrypt the plaintext password and a work factor. Bcrypt creates a random salt, performs an intentionally expensive transformation, and returns an encoded string that includes the algorithm version, cost, salt, and derived hash.
flowchart TD
A[Password at registration] --> B[Generate random salt]
B --> C[bcrypt with cost factor]
C --> D[Store encoded bcrypt hash]
E[Password at login] --> F[Read stored hash]
F --> G[bcrypt compare]
G --> H{Match?}
H -- Yes --> I[Authenticate]
H -- No --> J[Reject login]
The server stores the encoded bcrypt result, never the original password. During login, the comparison function reads the salt and cost embedded in that result, hashes the submitted password the same way, and compares safely.
Salts and Cost Factors
A salt is unique random data added before hashing. It ensures that two users who choose the same password do not receive the same stored hash. It also prevents an attacker from reusing one precomputed table against every account. The salt is not secret; bcrypt stores it with the hash.
The cost factor controls how much work bcrypt performs. Increasing the cost by one approximately doubles the work. That creates a deliberate trade-off: stronger resistance to offline guessing also makes legitimate login verification slower. Pick a cost that is acceptable for your hardware and traffic, measure it in production-like conditions, and revisit it as hardware changes.
Standard bcrypt accepts only the first 72 bytes of a password. Do not silently rely on that truncation: document the behavior, enforce an appropriate input policy, or use a modern password-hashing library that defines how longer inputs are handled. If you preprocess passwords, design and document that scheme carefully because an inconsistent migration can lock users out.
Hashing and Verifying Passwords
import bcrypt from "bcrypt";
const cost = 12;
export async function register(password) {
// Store only this derived value, never the plaintext password.
const passwordHash = await bcrypt.hash(password, cost);
await users.insert({ passwordHash });
}
export async function login(password, user) {
// compare() uses the salt and cost stored in user.passwordHash.
const matches = await bcrypt.compare(password, user.passwordHash);
return matches;
}
Use the library comparison function instead of implementing string comparison yourself. Also apply login rate limits, generic error messages, and monitoring; bcrypt protects stored credentials but does not stop online password guessing or account enumeration.
Choosing a Safe Work Factor
There is no universal number that fits every server. Benchmark the cost with representative hardware and choose the highest value that keeps authentication latency acceptable during peak traffic. When a user successfully logs in and the stored cost is below your current target, rehash their password with the newer cost and replace the stored hash. That improves security gradually without forcing a mass password reset.
Do not add a global secret pepper casually to application configuration and call the system finished. A pepper can add defense in depth when held outside the database, but it creates key-management and rotation obligations. Get the fundamentals right first: strong algorithm, unique salts, correct cost, TLS, rate limits, and secure reset flows.
Common Password Storage Mistakes
Encrypting passwords for later retrieval
Applications should not need the original password. Reversible storage turns one leaked key into full credential disclosure.
Using a fast hash alone
SHA-256, MD5, and similar fast hashes make offline guessing cheap. Password-specific algorithms intentionally spend more CPU and memory per guess.
Logging passwords or hashes
Never log request bodies containing credentials. Treat hashes as sensitive too: they can be used for offline guessing if exposed.
Forgetting password reset security
Reset tokens need high entropy, short expiry, single use, and the same careful logging and rate limiting as login endpoints.
Interview Questions
1. Why is bcrypt better than SHA-256 for passwords?
Bcrypt is intentionally slow and configurable, so each password guess costs attackers more work. SHA-256 is designed to be fast and is therefore unsuitable as the only password-hashing algorithm.
2. What does a salt protect against?
A unique salt makes identical passwords produce different hashes. It prevents an attacker from applying one precomputed lookup table or one recovered hash result across every user.
3. Should salts be secret?
No. Salts are stored alongside the hash. Their value comes from uniqueness, not secrecy; the password remains the unknown input.
4. How do you increase bcrypt security after deployment?
Increase the target cost after benchmarking, then rehash on successful login when an older stored hash is detected. This migrates active accounts without knowing anyone’s password in advance.
5. Does bcrypt prevent brute-force login attempts?
It slows offline guessing after a database leak. Online attacks still need rate limiting, abuse detection, MFA where appropriate, and safe generic responses.
Conclusion
Bcrypt stores a slow, salted, one-way representation instead of a recoverable password. Use its built-in hash and compare APIs, choose a measured cost factor, keep credentials out of logs, and pair password hashing with secure authentication and reset flows.
References
YouTube Videos
- “Password Hashing, Salting, and bcrypt” - Hussein Nasser
https://www.youtube.com/watch?v=0gsGN85usy0 - “How Password Hashing Works” - Computerphile
https://www.youtube.com/watch?v=_ulijANIMUs