SyntaxPilot
Courses/Cybersecurity Fundamentals/Lesson 14

Cybersecurity Fundamentals · Lesson 14 of 90 · 15 min

Storing passwords correctly

plaintext and encrypted password mistakessaltpepperrainbow tablesdictionary attackbrute-force attackcredential stuffingpassword sprayingslow hashingkey derivation function (KDF)work factorbcryptscryptArgon2id

These are the notes for Cybersecurity Fundamentals (defensive), episode 14. Last time a hashed 4-digit PIN fell in milliseconds. Today we fix that for passwords. The question is: how should a website store passwords so that a database leak is useless to an attacker? You'll build a login database the wrong way four times and watch each version get cracked: plaintext passwords, encrypted passwords, a fast unsalted hash (the dictionary attack, the brute-force attack and rainbow tables), and a salted fast hash. Then you'll invent the professional answer: slow hashing with a key derivation function (KDF) and a work factor (PBKDF2, bcrypt, scrypt, Argon2id), a pepper, defences against credential stuffing and password spraying, the NIST SP 800-63B password rules (length over complexity, breached-password checks) and password managers. Every term is explained the first time it appears, and the Glossary at the end defines them all again.

Riya, Aman, Ravi and their passwords are made up. Every code sample runs with Python 3.13 plus pip install bcrypt argon2-cffi (versions 5.0.0 and 25.1.0); outputs are real, copied from actual runs. Salts are random and timings depend on your computer, so those values will differ on your machine; the cracked / OK / rejected results and the error messages will match. In tracebacks, long file paths are shortened to just the file name.

The problems you'll solve

Problem Idea it teaches
Store passwords as typed Plaintext mistake (RockYou, 2009)
Encrypt them Why reversible storage fails
Hash them with SHA-256 Dictionary attack, brute force, rainbow tables
Same password, same hash Salt
A million guesses a second Slow hashing, KDF, work factor: PBKDF2, bcrypt, scrypt, Argon2id
One more wall Pepper
Attacks at the login page Online brute force, credential stuffing, password spraying
What rules to give users NIST SP 800-63B-4, blocklists, password managers

The one-line lesson: assume your database will leak, and store passwords so that the leak is useless.

Problem 1: plaintext passwords

At login a website must check your password. The obvious way is to store it exactly as typed: plaintext, meaning readable, unprotected text. Then a single bug, such as SQL injection (sneaking database commands through a web form; covered later in the course), lets an attacker read the whole users table.

This really happened. In December 2009 the company RockYou leaked the usernames and passwords of about 32 million users; the passwords were stored in plain text, and the attacker got in through an SQL injection flaw. That list of real passwords is still used by attackers as a wordlist today.

Demo 1: one leak shows everything

# a tiny site stores passwords as they are
users = {"riya": "chai@123", "aman": "Mumbai2024",
         "ravi": "chai@123"}

# one SQL injection later, the attacker dumps the table
for name, pw in users.items():
    print(name, "->", pw)

Output:

riya -> chai@123
aman -> Mumbai2024
ravi -> chai@123

Every password is readable, and because people reuse passwords, Riya's email and bank are now at risk too.

Problem 2: encrypt them?

Fix two: encrypt each password with AES before storing it.

Step Problem
Encryption is two-way With the key, every password comes back
The login server needs the key all the time So the key lives on, or next to, the same server
The attacker who steals the database usually steals the key Every password is exposed again
Staff with the key can read every password An insider risk (episode 4)

The insight: we never need the password back. We only need to check that what the user typed matches. That's a job for a one-way function: a hash (episode 13).

Problem 3: hashing with SHA-256

Fix three: store sha256(password). At login, hash what was typed and compare.

Demo 2: equal hashes and a dictionary attack

import hashlib

def h(pw): return hashlib.sha256(pw.encode()).hexdigest()

db = {"riya": h("chai@123"), "aman": h("Mumbai2024"),
      "ravi": h("chai@123")}
for name, digest in db.items():
    print(name, digest[:20])

words = ["123456", "password", "qwerty", "Mumbai2024",
         "iloveyou", "chai@123", "india123"]  # a wordlist
for name, digest in db.items():
    for w in words:
        if h(w) == digest:
            print("cracked", name, "->", w)

Output:

riya e0ac55b93f0722e99352
aman 710c30f69fdf01bcb5ea
ravi e0ac55b93f0722e99352
cracked riya -> chai@123
cracked aman -> Mumbai2024
cracked ravi -> chai@123

Two problems:

  1. Equal passwords give equal hashes. Riya and Ravi have the same hash, so cracking one cracks both, and an attacker can see who shares a password.
  2. Wordlists win. A dictionary attack hashes every word in a list of likely passwords and compares. A brute-force attack is its bigger cousin: trying every possible combination, not just a list.

Rainbow tables

Because sha256("chai@123") is the same on every website, attackers can hash billions of passwords once and keep the results, like a reverse phone book where you look up a number to find the name. Cracking a leak then needs no hashing at all, just a lookup.

Phone book Password cracking
A reverse phone book, printed once A precomputed table: hash → password
Look up any number in seconds Instant lookup, reused against every site
Clever compression fits it on a shelf A rainbow table: chains of hashes that trade a little lookup work for far less storage

To defeat precomputation, every user's hash must be different, even for the same password.

Problem 4: salt

A salt is a random value, created fresh for each user and stored next to the hash. We hash salt + password.

Demo 3: same password, different hashes

import hashlib, os

def h(salt, pw):
    return hashlib.sha256(salt + pw.encode()).hexdigest()

db = {}
for name in ("riya", "ravi"):           # same password!
    salt = os.urandom(16)               # new for every user
    db[name] = (salt.hex(), h(salt, "chai@123"))

for name, (salt, digest) in db.items():
    print(name, "salt", salt[:8], "hash", digest[:16])

Output (random, yours will differ):

riya salt 3fde2e1e hash d4ee46e8978b7f58
ravi salt 314b2ff5 hash 678e026e621cee16
  • os.urandom(16) gives 16 cryptographically secure random bytes (episode 10).
  • The salt is not secret. Its job is to make every hash unique: precomputed and rainbow tables become useless, and every user must be attacked separately.
  • But a salt does not slow down guessing one account.

Demo 4: how fast is guessing?

import hashlib, time, os

salt = os.urandom(16)
n, start = 0, time.perf_counter()
while time.perf_counter() - start < 1:     # one second
    hashlib.sha256(salt + b"guess%d" % n).digest()
    n += 1
print(f"{n:,} SHA-256 guesses/second, one core")

hours = 26 ** 8 / n / 3600               # 8 lowercase letters
print(f"every 8-letter password: {hours:.0f} hours")
print(f"on 100 cores: {hours / 100:.1f} hours")

Output (depends on your computer):

1,113,679 SHA-256 guesses/second, one core
every 8-letter password: 52 hours
on 100 cores: 0.5 hours
  • time.perf_counter() is a precise stopwatch.
  • 26⁸ ≈ 209 billion lowercase 8-letter passwords: about two days on one core of slow Python, half an hour on 100 cores, and graphics cards are far faster still.
  • SHA-256 was designed to be fast. For passwords, fast is the enemy.

Problem 5: slow hashing

Think of a bank locker whose dial takes one second per combination. The owner tries once: fine. A thief trying a million combinations needs 11.6 days.

Locker Password hashing
A dial that takes 1 second per try Slow hashing: each guess is deliberately expensive
The owner tries once A real user: one hash per login
A thief needs a million tries The attacker's cost multiplies
A dial you can make slower The work factor (cost), raised as computers get faster

The tool is a key derivation function (KDF): a function that turns a password into a hash or key with a tunable cost. OWASP (the Open Worldwide Application Security Project, a non-profit that publishes free web-security guides) gives a rule of thumb: one password hash should take under one second on your server.

Demo 5: PBKDF2

PBKDF2 (password-based key derivation function 2) simply runs HMAC (episode 12) many times in a row.

import hashlib, os, time

salt = os.urandom(16)
for iters in (1, 600_000):
    t = time.perf_counter()
    dk = hashlib.pbkdf2_hmac("sha256", b"chai@123",
                             salt, iters)
    ms = (time.perf_counter() - t) * 1000
    print(f"{iters:>7,} iterations: {ms:6.1f} ms")

Output (timings vary):

      1 iterations:    0.1 ms
600,000 iterations:  271.3 ms

600,000 iterations is OWASP's recommendation for PBKDF2-HMAC-SHA256 (220,000 for SHA-512). A user never notices a quarter of a second; the attacker's guess rate drops 600,000 times.

Demo 6: bcrypt

bcrypt (Provos and Mazières, USENIX 1999) is the classic password hash. Its cost is a power of two: each step up doubles the work.

import bcrypt, time

for cost in (10, 12):
    t = time.perf_counter()
    h = bcrypt.hashpw(b"chai@123", bcrypt.gensalt(cost))
    ms = (time.perf_counter() - t) * 1000
    print(f"cost {cost}: {ms:4.0f} ms  {h.decode()[:29]}...")

print(bcrypt.checkpw(b"chai@123", h))   # right password
print(bcrypt.checkpw(b"chai@124", h))   # wrong password

Output (salts and timings vary):

cost 10:   72 ms  $2b$10$IJMLBDqJnJKztepd8HIKMu...
cost 12:  277 ms  $2b$12$yBQ92AaYrwIvJGmFH/MoPe...
True
False
  • The stored string carries everything: $2b$ = the algorithm version, 12 = the cost, then 22 characters of salt, then the hash.
  • gensalt(cost) makes the salt for you; checkpw re-hashes with the stored salt and cost and compares.
  • OWASP: use bcrypt only for legacy systems, with a cost of at least 10.

Demo 7: bcrypt's 72-byte limit

import bcrypt

long_pw = "correct horse battery staple " * 3   # 87 chars
print(len(long_pw.encode()), "bytes")
bcrypt.hashpw(long_pw.encode(), bcrypt.gensalt())

Output:

87 bytes
Traceback (most recent call last):
  File "main.py", line 5, in <module>
    bcrypt.hashpw(long_pw.encode(), bcrypt.gensalt())
    ~~~~~~~~~~~~~^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
ValueError: password cannot be longer than 72 bytes, truncate manually if necessary (e.g. my_password[:72])

bcrypt reads at most 72 bytes. Older libraries silently ignored the rest (so two long passwords with the same first 72 bytes matched); this one refuses. Either cap input at 72 bytes or, better, use Argon2id.

Memory-hard hashing: scrypt and Argon2id

Attackers use GPUs (graphics cards), which have thousands of small cores guessing in parallel. PBKDF2 needs almost no memory, so it runs perfectly on them. A memory-hard function needs a lot of RAM for every guess, and RAM is expensive to attach to thousands of tiny cores.

Algorithm Idea OWASP minimum
Argon2id (first choice) Won the 2015 Password Hashing Competition; tunable time, memory and parallelism m = 19 MiB (19456 KiB), t = 2, p = 1
scrypt (if Argon2id is unavailable) Colin Percival, 2009: the first popular memory-hard KDF N = 2¹⁷ (128 MiB), r = 8, p = 1
bcrypt (legacy only) Slow but not memory-hard; 72-byte limit cost ≥ 10
PBKDF2 (when FIPS-140 compliance is required) HMAC repeated; FIPS-validated implementations exist 600,000 iterations (SHA-256)

(FIPS-140 is the US government standard for validated crypto modules. MiB is a mebibyte, 1,048,576 bytes.)

Demo 8: Argon2id

from argon2 import PasswordHasher
from argon2.exceptions import VerifyMismatchError

ph = PasswordHasher(memory_cost=19456, time_cost=2,
                    parallelism=1)        # OWASP minimum
stored = ph.hash("chai@123")
print(stored[:50], "...")

print(ph.verify(stored, "chai@123"))
try:
    ph.verify(stored, "chai@124")
except VerifyMismatchError as e:
    print("rejected:", e)

Output (the salt part differs every run):

$argon2id$v=19$m=19456,t=2,p=1$MQJ4N9mx1vY4K3owPGg ...
True
rejected: The password does not match the supplied hash
  • memory_cost is in KiB (19456 KiB = 19 MiB), time_cost is the number of passes, parallelism the number of threads.
  • The string records the algorithm (argon2id), version (v=19), settings, salt and hash, so you can raise the settings later and rehash each user at their next login (ph.check_needs_rehash(stored); see Practice 3).
  • A wrong password raises VerifyMismatchError. That's the protection working: catch it and show a generic "wrong username or password".

Problem 6: pepper

Salt Pepper
How many One per user One for the whole system
Secret? No Yes
Where it lives In the database, next to the hash Outside the database: a secrets vault or an HSM (hardware security module, a tamper-resistant device that holds keys)
What it stops Precomputed tables, spotting equal passwords Testing guesses when only the database leaks

A common pattern is argon2id(HMAC(pepper, password)). If the pepper itself leaks, it must be changed, and because old hashes can't be recomputed without the original password, every affected user must reset their password. OWASP calls a pepper defence in depth (layered protection, episode 3): an extra wall, never a replacement for a slow, salted hash.

Problem 7: attacks at the login page

With the database protected, attackers go to the front door.

Attack How it works Defences
Online brute force Many passwords against one account Slow down or lock the account after failures
Credential stuffing Username/password pairs leaked from another site, tried on yours; works because people reuse passwords MFA, breached-password checks, unusual-login detection
Password spraying One common password (e.g. Welcome@2026) tried once against thousands of accounts, so per-account lockouts never fire Rate limits across all accounts, blocklist common passwords, MFA

Note that perfect Argon2id can't stop credential stuffing: the attacker types the correct password. MFA (multi-factor authentication: something you know plus something you have or are, episode 29) is the strongest fix.

Problem 8: what rules to give users

NIST SP 800-63B is the US digital identity guideline for authentication; revision 4 was finalised in August 2025. Its password rules:

Rule NIST SP 800-63B-4
Minimum length, password as the only factor 15 characters
Minimum length, password used with MFA 8 characters
Maximum length Allow at least 64 characters; accept spaces and Unicode
Composition rules ("1 symbol, 1 capital, 1 digit") Must not be imposed
Forced periodic changes (every 90 days) Must not be required; force a change only on evidence of compromise
Blocklist New passwords must be checked against a list of common, expected or compromised values

Why no composition rules? They push people towards predictable patterns like P@ssw0rd1, then P@ssw0rd2 after a forced change. Length over complexity: chai at the station 6pm is far stronger than Ch@i1!.

Demo 9: a NIST-style policy checker

BLOCKLIST = {"password", "123456789012345", "qwertyuiopasdfg",
             "passwordpassword", "syntaxpilot2026"}

def check(pw, mfa):
    min_len = 8 if mfa else 15        # NIST SP 800-63B-4
    if len(pw) < min_len:
        return f"too short (min {min_len})"
    if pw.lower() in BLOCKLIST:
        return "too common, pick another"
    return "OK"                        # no symbol rules!

tests = [("Ch@i1!", False), ("passwordpassword", False),
         ("chai at the station 6pm", False), ("Ch@i1!xy", True)]
for pw, mfa in tests:
    print(f"{pw:24} mfa={mfa!s:5}", check(pw, mfa))

Output:

Ch@i1!                   mfa=False too short (min 15)
passwordpassword         mfa=False too common, pick another
chai at the station 6pm  mfa=False OK
Ch@i1!xy                 mfa=True  OK
  • f"{pw:24}" pads the text to 24 characters so the columns line up; {mfa!s:5} prints the boolean as text, padded to 5.
  • A real blocklist holds millions of leaked passwords (for example from public breach corpora), plus context words such as the company's name.

Password managers

Using one password everywhere is like one key for every door: lose it, and everything opens. A password manager is a locked key cabinet: an app that generates a long random password for every site, remembers it, and fills it in. You remember one strong master password, protected with MFA. Unique passwords everywhere make credential stuffing useless.

The whole chain

Step Problem Invention
1 Plaintext: one leak shows all Never store readable passwords
2 Encrypted: the key leaks too Store something you can only check
3 SHA-256: equal hashes, wordlists, tables Salt
4 A million guesses a second Slow hashing: KDF, work factor
5 GPUs Memory-hard: scrypt, Argon2id
6 Database-only leaks Pepper
7 Stuffing and spraying MFA, rate limits, blocklists
8 Bad user rules NIST: length over complexity; password managers

Common mistakes (and what they print)

Mistake What you see Why Fix
sha256(password), no salt cracked riya -> chai@123 Fast and unsalted Argon2id (salt built in)
Same salt for everyone Equal hashes for equal passwords Salt must be unique os.urandom(16) per user, or let the library do it
bcrypt.hashpw(87-byte password) ValueError: password cannot be longer than 72 bytes, truncate manually if necessary (e.g. my_password[:72]) bcrypt's input limit Argon2id, or cap at 72 bytes
Not catching ph.verify failures argon2.exceptions.VerifyMismatchError: The password does not match the supplied hash A wrong password raises try / except VerifyMismatchError
Different messages for "no such user" and "wrong password" Attackers learn which usernames exist Information leak One generic message
hashlib.scrypt(..., n=2**17) with default maxmem ValueError: [digital envelope routines] memory limit exceeded Default memory cap is too small Pass maxmem=256 * 1024 * 1024
Symbol rules + 90-day changes Users pick P@ssw0rd1, P@ssw0rd2 Predictable patterns 15+ characters, blocklist, no rotation

Mini project: a small, correct login system

Registration enforces NIST-style rules; passwords are peppered with HMAC and hashed with Argon2id; login uses one generic error message and upgrades old hashes.

import hmac, hashlib
from argon2 import PasswordHasher
from argon2.exceptions import VerifyMismatchError

PEPPER = b"load-me-from-a-secrets-vault"    # never stored in the DB
BLOCKLIST = {"passwordpassword", "123456789012345", "qwertyuiopasdfg"}
ph = PasswordHasher(memory_cost=19456, time_cost=2, parallelism=1)
db = {}                                      # username -> stored hash

def peppered(pw):
    return hmac.new(PEPPER, pw.encode(), hashlib.sha256).hexdigest()

def register(user, pw):
    if len(pw) < 15:
        return "rejected: use at least 15 characters"
    if pw.lower() in BLOCKLIST:
        return "rejected: too common"
    db[user] = ph.hash(peppered(pw))
    return "registered"

def login(user, pw):
    stored = db.get(user)
    if stored is None:
        return "wrong username or password"  # same message either way
    try:
        ph.verify(stored, peppered(pw))
    except VerifyMismatchError:
        return "wrong username or password"
    if ph.check_needs_rehash(stored):        # settings were raised
        db[user] = ph.hash(peppered(pw))
    return "welcome, " + user

print(register("riya", "chai@123"))
print(register("riya", "passwordpassword"))
print(register("riya", "chai at the station 6pm"))
print(login("riya", "chai at the station 6pm"))
print(login("riya", "chai at the station 7pm"))
print(login("ghost", "anything at all here"))
print(db["riya"][:31], "...")

Output:

rejected: use at least 15 characters
rejected: too common
registered
welcome, riya
wrong username or password
wrong username or password
$argon2id$v=19$m=19456,t=2,p=1$ ...
  • In a real app the pepper is loaded from a secrets manager or environment, never written in source code.
  • A real system would also rate-limit login attempts per account and per IP address, and offer MFA.

Practice

1. Homework: more memory. Time Argon2id with memory_cost=65536 (64 MiB) against the OWASP minimum.

Solution
import time
from argon2 import PasswordHasher

for mem in (19456, 65536):
    ph = PasswordHasher(memory_cost=mem, time_cost=2, parallelism=1)
    t = time.perf_counter()
    ph.hash("chai at the station 6pm")
    print(f"memory {mem // 1024} MiB: {(time.perf_counter() - t) * 1000:.0f} ms")

Output (timings vary):

memory 19 MiB: 41 ms
memory 64 MiB: 148 ms

More memory costs more time and more RAM per guess, which is what hurts GPU attackers. (argon2-cffi's own defaults are memory_cost=65536, time_cost=3, parallelism=4.)

2. scrypt in the standard library. Hash a password with OWASP's scrypt minimum.

Solution
import hashlib, os, time

salt = os.urandom(16)
t = time.perf_counter()
key = hashlib.scrypt(b"chai@123", salt=salt, n=2**17, r=8, p=1,
                     maxmem=256 * 1024 * 1024, dklen=32)
print(f"scrypt N=2^17: {(time.perf_counter() - t) * 1000:.0f} ms, {len(key)} bytes")

Output (timing varies):

scrypt N=2^17: 388 ms, 32 bytes

Without maxmem, OpenSSL refuses: ValueError: [digital envelope routines] memory limit exceeded. N = 2¹⁷ with r = 8 needs 128 MiB.

3. Upgrading old hashes. You raise Argon2id's settings. How do existing users move to the new settings without resetting passwords?

Solution
from argon2 import PasswordHasher

old = PasswordHasher(memory_cost=19456, time_cost=2, parallelism=1)
new = PasswordHasher(memory_cost=65536, time_cost=3, parallelism=1)

stored = old.hash("chai at the station 6pm")
print("needs rehash?", new.check_needs_rehash(stored))
new.verify(stored, "chai at the station 6pm")      # old hash still verifies
stored = new.hash("chai at the station 6pm")       # upgrade at login
print("needs rehash?", new.check_needs_rehash(stored))
print(stored[:31])

Output:

needs rehash? True
needs rehash? False
$argon2id$v=19$m=65536,t=3,p=1$

The old settings are stored inside the hash, so verification still works; right after a successful login (the only moment you have the plaintext) you rehash with the new settings.

4. Spot the attack. (a) 10,000 accounts each see one failed login with Welcome@2026. (b) One account sees 50,000 failed logins. (c) Many accounts log in successfully from a new country, using pairs from another site's leak.

Solution

(a) Password spraying. (b) Online brute force. (c) Credential stuffing. Defences: rate limits across accounts, account throttling, MFA, breached-password checks.

5. Salt or pepper? (a) Random, stored in the database, one per user. (b) One secret value kept in a vault. (c) Which one stops rainbow tables?

Solution

(a) Salt. (b) Pepper. (c) The salt: it makes every hash unique, so a precomputed table matches nothing.

6. Fix the policy. A company requires "8+ characters, one uppercase, one digit, one symbol, change every 90 days". Rewrite it per NIST SP 800-63B-4.

Solution

At least 15 characters (or 8 if MFA is always required), accept up to at least 64 characters including spaces and Unicode, no composition rules, no periodic changes (change only on evidence of compromise), and check every new password against a blocklist of common and breached passwords. Encourage password managers.

7. Why not just encrypt? Give two reasons encryption is the wrong tool for stored passwords.

Solution

(1) Encryption is reversible: whoever gets the key (an attacker on the same server, or an insider) reads every password. (2) You never need the password back, only to check it, so a one-way slow hash removes that risk entirely.

Quick quiz

Each user gets a random 16-byte salt stored next to their password hash. What does the salt mainly stop?

A. Guessing one user's password B. Rainbow tables and spotting equal passwords C. Credential stuffing D. The database leaking

Answer

B. A salt makes every hash unique, so precomputed (rainbow) tables fail and equal passwords look different. It doesn't slow guessing one account: that's the job of slow hashing and the work factor.

Interview questions

  1. How should passwords be stored? With a slow, salted, memory-hard password hash: Argon2id first (OWASP minimum m = 19 MiB, t = 2, p = 1), scrypt next, bcrypt for legacy systems, PBKDF2 (600,000 iterations with SHA-256) when FIPS-140 is required.
  2. Why not SHA-256 with a salt? It's designed to be fast: about a million guesses per second per core even in Python, far more on GPUs. Password hashes must be slow and ideally memory-hard.
  3. What's the difference between a salt and a pepper? A salt is random, per user and stored with the hash; it defeats precomputation. A pepper is a single secret kept outside the database; it's defence in depth if only the database leaks.
  4. What is a rainbow table? A compressed precomputed table mapping hashes back to passwords using hash chains. Unique salts make it useless.
  5. What is the work factor and how do you change it safely? The tunable cost (iterations, bcrypt cost, Argon2 memory/time), stored in the hash string. Raise it over time and rehash each user at their next successful login.
  6. Credential stuffing vs password spraying? Stuffing replays real leaked pairs from other sites; spraying tries one common password across many accounts. Defences: MFA, rate limiting across accounts, breached-password checks.
  7. What does NIST SP 800-63B-4 say about passwords? At least 15 characters for single-factor (8 with MFA), allow at least 64, no composition rules, no periodic rotation, blocklist checks for new passwords.
  8. Why is bcrypt's 72-byte limit a problem? Bytes after 72 are ignored (or rejected), so long passphrases can collide or fail; enforce a 72-byte maximum or use Argon2id.

Glossary

Term Meaning in plain words Example
Plaintext (password) Stored exactly as typed, readable by anyone who sees it riya -> chai@123
SQL injection Sneaking database commands through user input (covered later) How RockYou was breached
Credential Something that proves who you are, such as a username/password pair riya / chai@123
Encryption (two-way) Scrambling data so the key can turn it back AES-encrypted passwords: wrong tool
One-way function Easy to compute, infeasible to reverse A hash
Wordlist A list of likely passwords used for guessing The RockYou list
Dictionary attack Hashing every word in a wordlist and comparing Cracked all three users
Brute-force attack Trying every possible combination All 26⁸ lowercase 8-letter passwords
Precomputed table Hashes of many passwords computed in advance, reused across sites A reverse phone book
Rainbow table A compressed precomputed table built from chains of hashes Defeated by salts
Salt A random, per-user, non-secret value added before hashing os.urandom(16)
Pepper One secret value for all users, stored outside the database Kept in a vault or HSM
HSM Hardware security module: a tamper-resistant device that stores keys Holds the pepper
Slow hashing Making each hash deliberately expensive 0.25 s per guess
KDF (key derivation function) Turns a password (or secret) into a hash or key with a tunable cost PBKDF2, scrypt, Argon2
Work factor (cost) The setting that controls how slow a KDF is bcrypt cost 12, 600,000 iterations
PBKDF2 Password-based KDF 2: HMAC repeated many times hashlib.pbkdf2_hmac
Iteration One repetition of the inner function 600,000 for PBKDF2-SHA256
bcrypt Classic password hash (1999) with a power-of-two cost; 72-byte input limit $2b$12$...
scrypt Memory-hard KDF (2009) hashlib.scrypt
Argon2id Memory-hard KDF, winner of the 2015 Password Hashing Competition; first choice today $argon2id$v=19$m=19456,t=2,p=1$...
Memory-hard Needs lots of RAM per guess, which hurts GPU attackers Argon2id with 19 MiB
GPU Graphics card: thousands of small cores, great at parallel guessing Why PBKDF2 is weaker
MiB / KiB Mebibyte (1,048,576 bytes) / kibibyte (1,024 bytes) memory_cost=19456 KiB
Rehash Hashing again with new settings at the next successful login check_needs_rehash
VerifyMismatchError argon2-cffi's exception for a wrong password Catch it, say "wrong login"
OWASP Open Worldwide Application Security Project, publishes free security guides Password Storage Cheat Sheet
FIPS-140 US standard for validated crypto modules Why some must use PBKDF2
Online brute force Guessing many passwords against one account at the login page Stopped by throttling
Credential stuffing Trying username/password pairs leaked from other sites Works because of reuse
Password spraying One common password tried across many accounts Welcome@2026 × 10,000
Rate limiting Capping how many attempts are allowed per time period 5 tries per minute
MFA Multi-factor authentication: two or more kinds of proof (episode 29) Password + phone app
NIST SP 800-63B US digital identity guideline for authentication (revision 4: Aug 2025) 15-character minimum
Composition rules Rules like "one symbol, one capital" Forbidden by SP 800-63B-4
Blocklist A list of common, expected or breached passwords to reject passwordpassword
Breached-password check Rejecting passwords found in known leaks Part of the blocklist
Password manager An app that generates, stores and fills a unique password per site One master password + MFA

Summary

  • Assume the database leaks. Plaintext and encrypted passwords both expose everyone.
  • A fast hash like SHA-256 falls to dictionary attacks, brute force and rainbow tables.
  • A unique random salt defeats precomputation and hides equal passwords, but doesn't slow guessing.
  • Slow hashing with a KDF and a work factor makes each guess expensive; memory-hard functions hurt GPUs.
  • Use Argon2id (OWASP minimum m = 19 MiB, t = 2, p = 1); scrypt next; bcrypt is legacy (72-byte limit); PBKDF2 (600,000 iterations) where FIPS is required. Raise costs and rehash at login.
  • A pepper adds depth when only the database leaks.
  • Defend the login page against brute force, credential stuffing and password spraying with rate limits, MFA and breached-password checks.
  • NIST SP 800-63B-4: 15+ characters (8 with MFA), allow 64+, no composition rules, no forced rotation, blocklists. Encourage password managers.

Next episode: asymmetric cryptography and key exchange: public and private keys, RSA, elliptic curves, Diffie-Hellman, forward secrecy and hybrid encryption.

Sources: The Register, "RockYou hack exposes names, passwords of 32m accounts" (17 Dec 2009); OWASP Password Storage Cheat Sheet; NIST SP 800-63B-4 (Aug 2025), as quoted by Enzoic ("NIST SP 800-63B Rev 4") and drupal.org issue 1592202; Provos and Mazières, "A Future-Adaptable Password Scheme", USENIX 1999; Colin Percival, "Stronger key derivation via sequential memory-hard functions", BSDCan 2009. Code outputs from Python 3.13, bcrypt 5.0.0 and argon2-cffi 25.1.0. Fetched 29 Oct 2026.