How Password Hashing Systems Work
- Author
- Prathamesh Patil
- Length
- 2214 words
- Read
- 10 min
Key takeaways
Password hashing is a one‑way transformation; the original password cannot be recovered from the stored value.
A salt is a random per‑password value that prevents attackers from reusing pre‑computed rainbow tables and from detecting identical passwords across accounts.
Key‑stretching (or work‑factor) makes each hash computation deliberately expensive, turning a fast offline cracking attempt into a costly operation.
Modern password‑hashing algorithms (e.g., bcrypt, scrypt, Argon2) combine salts, configurable work factors, and memory‑hard designs to resist GPU/ASIC‑accelerated attacks.
Precise Definition of Password Hashing
Password hashing is a cryptographic primitive that converts a user‑supplied secret into a fixed‑size digest using a deliberately slow, one‑way function. Unlike encryption, there is no decryption key; the system never needs to retrieve the original password. The primary security goals are:
Irreversibility – the hash function is designed so that, given the output, finding any input that maps to it is computationally infeasible.
Uniqueness per credential – each stored hash incorporates a unique salt, ensuring that two users with the same password produce different digests.
Computational hardness – a configurable work factor (often expressed as a number of iterations or a memory cost) forces an attacker to spend significant CPU or memory resources per guess.
Salting and key‑stretching are not optional add‑ons; they are integral to the definition of a secure password‑hashing scheme. Without a salt, an attacker can pre‑compute a table of hashes for common passwords (a rainbow table) and instantly reverse many stored values. Without stretching, the hash function is too fast, allowing an attacker to test billions of guesses per second on commodity hardware.
How Password Hashing Works at a Glance (60‑Second Overview)

User → Salt Generation → Hash Function → Stored Record
User submits a password via a TLS‑protected channel.
Server generates a cryptographically random salt (typically several bits or more).
Hash function (e.g., Argon2id) runs with the supplied password, the generated salt, and a configured work factor.
Resulting record stores the salt, work‑factor parameters, and the resulting digest in a single string (often using a
$‑delimited format).
The system never persists the plaintext password; verification repeats the same steps with the stored salt and parameters, then compares the newly computed digest to the stored one.
Why Simple Hashing Fails: The Naïve Approach and Its Pitfalls
Using a fast, general‑purpose hash like SHA‑several or MD5 without a salt or work factor is insecure for two main reasons:
Rainbow‑table vulnerability – Unsalted hashes are deterministic; the same password always yields the same digest. Attackers can pre‑compute massive tables of common passwords and their hashes, then look up any stolen hash instantly.
Speed enables brute force – Functions such as SHA‑several are optimized for speed, allowing modern GPUs to compute billions of hashes per second. An attacker with a stolen password database can therefore try a huge number of guesses in a short time.
Failure domains and blast radius

Name the parts of this system whose failure changes the outcome, and what each failure does to work already in flight. Cover control-plane loss, data-plane loss, a partition between them, and what cannot be reconstructed if the decision log is gone. Do not paste an edge-network or PoP list unless this article is about an edge network.
Mechanics of Secure Password Hashing: Salts, Work Factors, and Memory‑Hard Functions
Modern password‑hashing algorithms combine three protective mechanisms:
Unique per‑password salt – Random data concatenated (or otherwise mixed) with the password before hashing. This eliminates cross‑user hash collisions and forces attackers to treat each password independently.
Work factor (cost) – A configurable parameter that controls the number of iterations or the amount of memory used. Raising the cost linearly increases the time required for each guess, throttling brute‑force attempts.
Memory‑hard design – Algorithms like scrypt and Argon2 require a substantial amount of RAM during computation, making parallel GPU/ASIC attacks far less efficient because memory cannot be scaled as cheaply as raw compute.
By embedding the salt and work‑factor metadata alongside the digest, the system can verify passwords without external configuration, while still allowing administrators to increase the cost over time as hardware improves.
FAQ
1. How is the salt stored?
The salt is typically concatenated with the hash output in a standardized string format (e.g., $argon2id$v=several$m=several,t=3,p=2$<salt>$<hash>). This allows verification code to extract the salt and parameters directly from the stored value.
2. Can I reuse a salt across users? No. Reusing salts defeats the primary purpose of preventing cross‑user hash collisions and enables attackers to reuse pre‑computed tables across multiple accounts.
3. What is a reasonable work factor? The appropriate cost depends on the target platform’s performance. The recommendation is to select the highest cost that yields a verification latency of a few hundred milliseconds on typical production hardware. The exact number is not published in the public docs and should be measured locally.
4. Are bcrypt, scrypt, and Argon2 interchangeable? All three provide salts and configurable work factors, but Argon2 adds explicit memory‑hard parameters, making it more resistant to modern GPU/ASIC attacks. The choice often depends on language support and compliance requirements.
5. How do I migrate from an old hashing scheme? A common pattern is “hash‑on‑read”: when a user logs in, verify the legacy hash; if it succeeds, re‑hash the password with the new algorithm and store the updated record. This approach upgrades passwords gradually without forcing a reset.
6. Does password hashing protect against server‑side breaches? It mitigates the impact by ensuring that stolen hashes are computationally expensive to reverse. However, if an attacker gains access to the server’s runtime memory, they may capture plaintext passwords before hashing. Defense‑in‑depth (e.g., TLS, rate limiting, monitoring) remains essential.
Key‑Stretching Algorithms and Their Parameters
Password‑hashing libraries typically expose a work‑factor (sometimes called cost, iterations, or memory‑size) that controls how much effort a verifier must expend to derive the final hash. The work‑factor is deliberately tunable so operators can balance security against latency on their own hardware.
| Algorithm | Primary Work‑Factor | What It Controls |
|---|---|---|
| PBKDF2 | iterations |
Number of HMAC‑SHA‑* rounds* applied to the password+salt |
| bcrypt | cost (log₂ rounds) |
Number of Blowfish‑based key‑expansion rounds; each increment roughly doubles CPU time |
| scrypt | N, r, p |
N is a CPU‑hard memory‑hard factor; r and p tune parallelism and block size |
| Argon2 | time, memory, parallelism |
Explicit CPU time, memory consumption, and thread count |
Why the work‑factor matters
The work‑factor is stored alongside the salt in the final hash string (e.g.,
$argon2id$v=several$m=several,t=3,p=2$…). This makes the verification path deterministic: the server reads the parameters, re‑executes the algorithm with the supplied password, and compares the result.Raising the work‑factor makes each guess more expensive for an attacker, directly increasing the cost of offline cracking attempts.
Choosing a baseline
Public guidance from the OWASP Password Storage Cheat Sheet recommends selecting the highest work‑factor that your production latency budget can tolerate. The cheat sheet does not publish a specific number because acceptable latency varies with hardware, request volume, and language runtime. In practice, many services start with bcrypt cost=several or Argon2 time=2, memory=a limited memory budget (see current vendor docs) and then benchmark against their own latency SLA.
Implementation tip
When using a library that abstracts the algorithm (e.g., passlib for Python or bcrypt for Node.js), let the library generate the salt and embed all parameters in the output string. Store that string verbatim in your user table; on verification, pass the stored string back to the library’s verify function. This eliminates the risk of mismatched parameters across deployments.
Example: Verifying a Password with Argon2id
Below is a minimal, language‑agnostic illustration of the verification flow that most Argon2 libraries expose. The code mirrors the pattern shown in the official Argon2 reference implementation.
function verifyPassword(storedHash, candidatePassword):
// storedHash format: $argon2id$v=19$m=65536,t=3,p=2$<base64(salt)>$<base64(hash)>
parts = split(storedHash, '$')
params = parseParams(parts[3]) // extracts m, t, p
salt = base64Decode(parts[4])
expectedHash = base64Decode(parts[5])
// Re‑run Argon2id with the same parameters
computedHash = argon2id(
password = candidatePassword,
salt = salt,
memory = params.m,
time = params.t,
threads = params.p
)
return constantTimeCompare(computedHash, expectedHash)
Key observations
The salt and all work‑factor parameters travel with the stored hash, so the verifier does not need any external configuration.
A constant‑time comparison prevents timing side‑channels that could leak partial hash information.
The function fails fast if the stored hash is malformed, which is useful for detecting data‑corruption bugs.
Common Pitfalls and How to Avoid Them
| Pitfall | Why It Happens | Mitigation |
|---|---|---|
| Re‑using a static salt across users | Developers sometimes generate a single global salt at startup to avoid per‑user storage. | Generate a fresh, cryptographically random salt per password; store it with the hash. |
| Choosing an overly low work‑factor | Default library settings may be tuned for development speed rather than production security. | Benchmark the hash function on your production hardware and raise the cost until latency meets your SLA. |
| Storing the raw hash output without parameters | Some legacy schemas only keep the binary hash column, losing the cost and salt. | Migrate to a format that concatenates algorithm identifier, cost, salt, and hash (e.g., the $algorithm$... string). |
| Using a fast general‑purpose hash (SHA‑several, MD5) as the sole protector | These functions are designed for speed; GPUs can compute billions of guesses per second. | Replace them with a dedicated password‑hashing algorithm that is intentionally slow and memory‑hard. |
| Neglecting to rotate parameters after a major hardware upgrade | Faster CPUs can reduce the effective cost of an existing work‑factor, making hashes easier to crack. | Periodically re‑hash stored passwords with a higher work‑factor during successful login (the “hash‑on‑read” pattern). |
| Logging the full hash string | Log aggregation pipelines may inadvertently capture the entire $algorithm$... string, exposing salts and work‑factors. |
Mask or omit password‑hash fields from logs; treat them as sensitive as plaintext passwords. |
What the Public Docs Emphasize
One‑wayness – The hash function must be irreversible; the stored value should never be convertible back to the original password.
Salt uniqueness – Each password entry gets its own random salt, thwarting pre‑computed attacks.
Adjustable cost – The work‑factor should be configurable and regularly revisited as hardware evolves.
These principles are reiterated across the OWASP Password Storage Cheat Sheet, the Argon2 RFC, and the official bcrypt documentation. None of the sources provide a universal “best” cost value; they all stress measuring impact on your own latency budget.
How Salting and Key‑Stretching Work
When a user creates or updates a password, the system performs three distinct steps before persisting anything:
Generate a cryptographically‑random salt – a short byte string (typically several bits) that is unique per password entry.
Combine the salt with the plaintext password – the salt is concatenated (or otherwise mixed) with the password so that the resulting input to the hash function is different even for identical passwords.
Frequently Asked Questions
- Do I need to store the salt in a separate database column?
No. Public implementations (bcrypt, Argon2) embed the salt in the encoded hash string. Keeping them together eliminates synchronization bugs.
- Can I use a fast hash like SHA‑several with a salt instead of a dedicated password‑hashing algorithm?
Not advisable. SHA‑several is designed for speed, which is exactly what attackers exploit. Memory‑hard functions deliberately slow down each guess, providing a higher security margin.
- How often should I rotate the cost parameter?
The OWASP cheat sheet suggests revisiting the cost whenever hardware improves significantly (e.g., a new CPU generation) or when you observe that authentication latency has room to increase without harming user experience.
- Is Argon2 always better than bcrypt?
Argon2 offers configurable memory usage and is the winner of the several Password Hashing Competition, but bcrypt remains widely supported and battle‑tested. Choose based on library availability, runtime constraints, and compliance requirements.
- What happens if an attacker obtains the database dump?
They gain the salts, cost parameters, and hashes, but without the original passwords they must still perform a brute‑force attack. The difficulty of that attack is directly proportional to the chosen work factor and memory hardness.
- Can I store password hashes in a client‑side cookie for offline login?
No. Password hashes are meant for server‑side verification only. Exposing them to the client defeats the purpose of one‑way protection and opens avenues for replay attacks.
Key takeaways
Password hashing is a one‑way, salted, key‑stretched transformation designed for secure storage.
Salting guarantees uniqueness; key‑stretching (via configurable cost and memory hardness) makes brute‑force attacks expensive.
Use a memory‑hard algorithm (bcrypt, scrypt, Argon2) and store the full encoded string (algorithm, cost, salt, hash) together.
Regularly benchmark and adjust the work factor to keep authentication latency acceptable while staying ahead of hardware improvements.
Avoid common pitfalls such as static salts, low cost settings, and non‑constant‑time comparisons.
Sources
Consistent hashing - Reducing the Scope of Impact with Cell-Based Architecture
Consistent hashing - Reducing the Scope of Impact with Cell-Based Architecture
How DeepL keeps closest-exit routing during maintenance with AWS Cloud WAN
Cross-request KV cache exposure in the GLM-5.3 Workers AI model, and our remediation with SGLang
Origin Range Requests: Serving large files without range-request tuning
Image credits
- Cover: AI-generated illustration