Skip to content
Tutorials Center
My learning

Topics

Lesson 18 of 80 ยท Authentication and Access Control

Password Storage Done Right

Learn why plain and fast hashes fail for passwords, how salts, peppers and slow key derivation work, and how to store and verify passwords safely in Python.

Sooner or later every database leaks. Maybe through a SQL injection bug, a forgotten backup, or a stolen laptop. When that happens, the way you stored passwords decides whether the incident is an embarrassment or a catastrophe. If passwords were stored in plain text, every account is lost at once, and because people reuse passwords, accounts on other sites are lost too.

The goal of password storage is simple to state: after a breach, an attacker should have to spend a large, unavoidable amount of work for each guess against each user. This lesson shows why ordinary hashes do not achieve that, and what does: a unique salt per password, a deliberately slow key-derivation function, an optional pepper, and a constant-time comparison. You should already know what a hash is (Hash Functions and Integrity) and how to compare secrets safely (HMAC and Message Authentication).

Why plain and fast hashes fail

A hash is one-way, so storing SHA-256(password) sounds safe. It is not, for three reasons.

  1. Identical passwords give identical hashes. An attacker who steals the table sees at a glance which users share a password, and cracking one cracks all of them.
  2. Hashes can be precomputed. The attacker hashes millions of common passwords once (a lookup table, or a more compact rainbow table) and then finds your users' hashes by a simple lookup.
  3. SHA-256 is fast on purpose. A single modern GPU can compute billions of SHA-256 hashes per second. Fast is great for file integrity and terrible for passwords, because speed is exactly what a guessing attacker wants.

This demo uses a fake leaked table and a tiny wordlist to show points 1 and 2:

Python Cracking unsalted hashes

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Two of four users fell with a seven-word list, and the strongest-looking password survived only because it was not on the list. Real wordlists hold billions of entries from earlier breaches.

Salts: a unique random value per password

A salt is a random value, generated fresh for every password and stored next to the hash. The hash is computed over salt + password. Salts are not secret; their job is to make every stored hash unique:

  • Two users with the same password get different hashes, so the attacker cannot spot reuse.
  • Precomputed tables become useless, because the attacker would need a separate table for every possible salt.
  • The attacker must attack each user separately, which multiplies the cost by the number of accounts.

Use at least 16 random bytes from a cryptographically secure source (secrets.token_bytes(16) or os.urandom(16)), never a username, an email address or a timestamp.

Python Salts make every hash unique

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Salting alone is not enough. The last loop still cracked Alice after five guesses, because one SHA-256 is so cheap that an attacker can try billions of words per second per account. The remedy is to make each guess expensive.

Slow, memory-hard key derivation

A password hashing function (also called a key-derivation function, KDF) has a tunable cost so that a single hash takes, say, 100 ms instead of a microsecond. That is unnoticeable for a user who logs in once, and devastating for an attacker who needs billions of guesses. The main choices:

Function Cost knob Notes
PBKDF2-HMAC-SHA256 iteration count Ubiquitous and standardized (FIPS-friendly). CPU-only, so GPUs speed it up well. OWASP currently recommends at least 600,000 iterations.
bcrypt cost factor (work doubles per step) Old and battle-tested. Truncates input at 72 bytes. A cost of 10 or more is typical.
scrypt CPU/memory factor N, block size r, parallelism p Memory-hard: each guess needs lots of RAM, which limits GPU and ASIC parallelism.
Argon2id time, memory, parallelism The winner of the Password Hashing Competition and the usual first choice for new systems. Combines memory-hardness with side-channel resistance.

If you can choose freely, pick Argon2id; if you need standards compliance, PBKDF2; otherwise scrypt or bcrypt are fine. The one choice that is never fine is a general-purpose hash such as MD5, SHA-1 or SHA-256 used alone.

Memory-hardness matters because attackers use massively parallel hardware. A GPU has thousands of tiny cores but little memory per core. If every guess needs 64 MiB of RAM, only a small number of guesses can run at once, which removes the hardware advantage.

The browser-based Python on this site does not include hashlib.pbkdf2_hmac or hashlib.scrypt, so the demos here use a small, clearly labelled pure-Python stand-in for PBKDF2 (it produces exactly the same output as the real function, just more slowly). In your own projects, call the standard library:

Python
import hashlib, os

salt = os.urandom(16)

# PBKDF2 from the standard library
key = hashlib.pbkdf2_hmac("sha256", b"correct horse", salt, 600_000, dklen=32)

# scrypt from the standard library (needs OpenSSL 1.1+)
# n = CPU/memory cost (a power of two), r = block size, p = parallelism.
# Memory used is about 128 * n * r bytes: here 128 * 32768 * 8 = 32 MiB.
key = hashlib.scrypt(b"correct horse", salt=salt, n=2**15, r=8, p=1,
                     maxmem=64 * 1024 * 1024, dklen=32)

# Argon2id needs a package, for example argon2-cffi:
#   from argon2 import PasswordHasher
#   ph = PasswordHasher()           # sensible Argon2id defaults
#   stored = ph.hash("correct horse")
#   ph.verify(stored, "correct horse")

The stand-in below implements PBKDF2 following RFC 8018 and checks itself against the published test vector for SHA-256, one iteration. Then it shows that the iteration count scales the work.

Python PBKDF2 stand-in and the cost knob

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Peppers: a secret the database does not hold

A pepper is a secret value shared by all passwords, kept outside the database (in an environment variable, a secrets manager or a hardware security module). If the attacker steals only the database, for example through SQL injection, the pepper is missing and cracking is impossible, however weak the passwords are.

A common pattern is to compute HMAC(pepper, password) first and then feed the result into the slow hash. Peppers help only if the pepper really lives somewhere else, and they make rotation harder, so treat them as a defense-in-depth extra, never as a replacement for salts and slow hashing. See Randomness, Key Management and Secrets for how to keep such secrets.

A complete store-and-verify design

Putting the pieces together, a good implementation stores one self-describing string. Recording the algorithm and cost in the string lets you raise the cost later and upgrade old hashes the next time each user logs in.

sequenceDiagram
    participant U as User
    participant S as Server
    participant D as Database
    U->>S: email + password
    S->>D: fetch stored string
    D-->>S: algorithm$cost$salt$hash
    S->>S: derive key from password and stored salt and cost
    S->>S: compare in constant time
    alt match and cost is outdated
        S->>D: store a fresh hash with the new cost
    end
    S-->>U: success or the same generic error

Verification re-derives the key with the stored salt and cost, compares in constant time and upgrades outdated hashes.

Python Store, verify and upgrade a password hash

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

The tuple (ok, needs_upgrade) is the pattern most frameworks use: after a successful login you hold the plain password for a brief moment, which is the only chance to re-hash it with stronger settings.

Practical rules

  • Never invent a scheme. Use your framework's built-in password hasher (Django, Laravel, Spring Security and others all ship one) or a well-known library.
  • Tune the cost so that one hash takes roughly 100-500 ms on your production hardware, then re-check every year or two.
  • Set a maximum password length (for example 128 characters or more) to avoid denial of service through gigantic inputs, but allow long passphrases, spaces and any Unicode character.
  • Return the same generic error for "unknown user" and "wrong password", and spend similar time on both, so attackers cannot enumerate accounts.
  • Never log passwords, never email them, and never store security-question answers as plain text. A reset flow should send a one-time token instead.
  • Rate-limit logins and consider multi-factor authentication so that a cracked password alone is not enough.

Rainbow tables and the time-memory trade-off

A rainbow table is a precomputed lookup structure that lets an attacker reverse unsalted hashes quickly. A plain lookup table of every password and its hash is huge. A rainbow table stores only chains: it repeatedly hashes a value and applies a "reduction" function that turns a hash back into a candidate password, saving just the start and end of each chain. To look up a hash the attacker recomputes part of the chain and finds a matching end. This is the time-memory trade-off: spend more computation per lookup to use far less storage.

Rainbow tables only work when the hash is fast and unsalted. A unique random salt per password makes every precomputed table useless, because the attacker would need a separate table per salt. Slow password hashes (bcrypt, scrypt, Argon2) make even the chain computation costly. That is why the earlier sections insist on both. Never store passwords with plain MD5 or SHA-1 and never reuse a salt.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Why is a single unsalted SHA-256 a poor way to store passwords?

    SHA-256 is not reversible and handles any bytes, but it is extremely fast, so guessing is cheap. Without a salt, equal passwords give equal hashes and precomputed tables work.
  2. 2. What is the main purpose of a per-password salt?

    A salt is random, unique and stored openly beside the hash. It forces per-user attacks but does not make a single guess slower; that is the job of a slow KDF.
  3. 3. Which statement about a pepper is correct?

    A pepper is a global secret held elsewhere (environment, vault or HSM). It adds defense in depth but does not replace salts or slow hashing.
  4. 4. Why is memory-hardness (scrypt, Argon2) valuable?

    Each guess needs a large block of RAM, and parallel hardware has little memory per core, so cheap massive parallelism is no longer possible.
  5. 5. A user logs in successfully and their stored hash uses an old, weaker cost. What should the server do?

    At login you briefly hold the correct password, which is the only time you can upgrade the hash transparently. Storing the algorithm and cost inside the record makes this possible.

Summary

  • Fast, unsalted hashes let attackers use lookup tables and spot reused passwords; a leak then exposes most accounts.
  • Give every password a unique random salt (16 bytes or more) and store it beside the hash.
  • Use a slow, tunable function: Argon2id first, otherwise scrypt, bcrypt or PBKDF2 with high iteration counts.
  • Add an optional pepper kept outside the database, and compare hashes in constant time.
  • Store algorithm, cost, salt and hash in one string so you can upgrade hashes at the next login.
  • Use your framework's built-in hasher, return generic errors, and combine good storage with rate limiting and MFA.

Next: Password Strength and Policies, where you'll learn what makes a password hard to guess in the first place.