← Back to FastAPI
Lesson 6.2 · Auth & Security

Password Hashing

Never store passwords - store hashes. Use pwdlib with Argon2: hash at signup, verify at login, and upgrade old hashes on the fly. Measured: Argon2 takes about 43 ms per guess, SHA-256 makes 2 million guesses a second. And two real leaks we found and fixed: login timing told attackers which usernames exist, and the 422 error echoed the password back.

Intermediate35 min

What you will be able to do

  • Explain why passwords must be hashed, and why with a slow hash
  • Hash and verify passwords with pwdlib and Argon2
  • Read an Argon2 hash string
  • Build signup and login endpoints that never store or return the password
  • Stop user enumeration through timing
  • Keep passwords out of error responses

The idea, in plain English

Databases leak - through bugs, backups, or stolen laptops. If they hold passwords, every user is exposed, and on other sites too, because people reuse passwords. So you never store the password. You store a hash: the result of a one-way function. At login you hash what the user typed and compare. You can check a password, but not read it back.

Not every hash is good for this. SHA-256 is built to be fast - great for files, terrible for passwords, because an attacker with your hashes can try millions of guesses per second. Password hashes like Argon2 are slow on purpose and add a random salt, so the same password gives a different hash each time.

We measure that difference, build signup and login on SQLite, and attack our own login - finding two leaks that many real APIs have. pwdlib 0.3.1 with argon2-cffi 25.1.0, FastAPI 0.143.0.

Worked example: A signup and login API that stores Argon2 hashes in SQLite - attacked with a timing test and a short password, then fixed.

workflowSignup and loginstep 1 / 3

1 - Signup

The password is hashed with a new random salt. Only the hash is stored.

same password twice
two different hashes
answer
{"id":1,"username":"ravi"}

The password is hashed at signup and checked at login - never stored. Real results from our API.

Words you will see in this lesson

A few words about passwords.

Small dictionary
HashThe output of a one-way function. Easy to make, impossible to turn back.
SaltRandom data mixed in before hashing, so equal passwords get different hashes.
Argon2A modern password hash, slow and memory-hungry on purpose.
Brute forceTrying password after password until one matches.
User enumerationFinding out which usernames exist on a site.
Timing attackLearning a secret from how long the server takes to answer.

An everyday example: a fingerprint lock

  • A fingerprint lock does not keep a photo of your finger - only a pattern made from it. From the pattern nobody can rebuild your finger.
  • When you touch it, it makes the pattern again and compares.
  • A good lock is a little slow to answer, so a thief cannot try a thousand fingers a minute.
  • And it says only "no" - never "this finger is not registered" versus "wrong finger".

Example 1 - hashing and verifying

hashing.py tries pwdlib and compares it with a plain SHA-256:

  • PasswordHash.recommended() gives Argon2 with safe settings.
  • The same password hashed twice gave two different hashes - a new salt each time. With SHA-256 the two were equal, so an attacker sees at once who shares a password.
  • verify returned True for the right password and False for "Monsoon2026" - one capital letter.
  • Argon2 took about 43 ms per hash on this laptop: about 23 guesses a second. SHA-256 did 1,000,000 hashes in 0.48 s: about 2 million guesses a second - roughly 90,000 times more.
Example 1 - hashing.py
import hashlib import time from pwdlib import PasswordHash password_hash = PasswordHash.recommended() # Argon2 with safe settings # 1. Hash the same password twice h1 = password_hash.hash("monsoon2026") h2 = password_hash.hash("monsoon2026") print("hash 1:", h1) print("hash 2:", h2) print("same? ", h1 == h2) # 2. Check passwords against a stored hash print("right password:", password_hash.verify("monsoon2026", h1)) print("wrong password:", password_hash.verify("Monsoon2026", h1)) # 3. How long does one hash take? start = time.perf_counter() for _ in range(10): password_hash.hash("monsoon2026") argon_ms = (time.perf_counter() - start) / 10 * 1000 print(f"argon2: {argon_ms:.0f} ms per hash -> about {1000 / argon_ms:.0f} guesses per second") # 4. Compare: a plain fast hash (what NOT to use) start = time.perf_counter() for i in range(1_000_000): hashlib.sha256(f"guess{i}".encode()).hexdigest() sha_s = time.perf_counter() - start print(f"sha256: 1,000,000 hashes in {sha_s:.2f} s -> about {1_000_000 / sha_s:,.0f} guesses per second") print("sha256 of the same password twice:", hashlib.sha256(b"monsoon2026").hexdigest() == hashlib.sha256(b"monsoon2026").hexdigest())
Output
hash 1: $argon2id$v=19$m=65536,t=3,p=4$m9bvQ/0CLwt/vmJwuzCV6g$YN0Yenby/xdjObzJlH1+Gx4JQQvlXVkyWlKEwOJ7f+Q hash 2: $argon2id$v=19$m=65536,t=3,p=4$GjEAjTomf0nI/XOuefptMg$njhMZoTQWRWfEzVuL5RkF92XraFN7wg0I6TyrBEhGjI same? False right password: True wrong password: False argon2: 43 ms per hash -> about 23 guesses per second sha256: 1,000,000 hashes in 0.48 s -> about 2,076,311 guesses per second sha256 of the same password twice: True

Reading an Argon2 hash

A hash string carries everything verify needs, separated by $:

  • argon2id - the algorithm.
  • v=19 - the version.
  • m=65536,t=3,p=4 - the cost: 64 MB of memory, 3 passes, 4 lanes.
  • Then the salt, then the hash itself.
  • So you store ONE text column, and old hashes still work after you change the settings.

Example 2 - signup and login

accounts.py stores users in SQLite:

  • User has hashed_password - there is no password column at all.
  • signup hashes the password, checks the username is free (409 if not), and answers with UserPublic - no hash.
  • login uses ONE message for "no such user" and "wrong password", so the answer text does not tell which.
  • DUMMY_HASH and hide_inputs are the two fixes explained below.
Example 2 - accounts.py
from contextlib import asynccontextmanager from typing import Annotated from fastapi import Depends, FastAPI, HTTPException, Request from fastapi.encoders import jsonable_encoder from fastapi.exceptions import RequestValidationError from fastapi.responses import JSONResponse from pwdlib import PasswordHash from sqlmodel import Field, Session, SQLModel, create_engine, select password_hash = PasswordHash.recommended() engine = create_engine("sqlite:///users.db") DUMMY_HASH = password_hash.hash("not-a-real-password") # for users that do not exist class User(SQLModel, table=True): id: int | None = Field(default=None, primary_key=True) username: str = Field(unique=True, index=True) hashed_password: str # never the password itself class SignUp(SQLModel): username: str = Field(min_length=3, max_length=30) password: str = Field(min_length=8, max_length=128) class UserPublic(SQLModel): id: int username: str # no hash in the answer def get_session(): with Session(engine) as session: yield session SessionDep = Annotated[Session, Depends(get_session, scope="function")] @asynccontextmanager async def lifespan(app: FastAPI): SQLModel.metadata.create_all(engine) yield app = FastAPI(lifespan=lifespan) @app.exception_handler(RequestValidationError) def hide_inputs(request: Request, exc: RequestValidationError): # never echo a password back errors = [{k: v for k, v in e.items() if k != "input"} for e in exc.errors()] return JSONResponse(status_code=422, content={"detail": jsonable_encoder(errors)}) @app.post("/signup", response_model=UserPublic, status_code=201) def signup(data: SignUp, session: SessionDep): if session.exec(select(User).where(User.username == data.username)).first(): raise HTTPException(status_code=409, detail="Username taken") user = User(username=data.username, hashed_password=password_hash.hash(data.password)) session.add(user) session.commit() session.refresh(user) return user @app.post("/login") def login(data: SignUp, session: SessionDep): user = session.exec(select(User).where(User.username == data.username)).first() stored = user.hashed_password if user else DUMMY_HASH # always do the slow check password_ok = password_hash.verify(data.password, stored) if user is None or not password_ok: raise HTTPException(status_code=401, detail="Wrong username or password") # one message for both return {"message": f"Welcome back, {user.username}"}
try_accounts.py
from fastapi.testclient import TestClient from accounts import app with TestClient(app) as c: for label, url, body in [ ("signup ravi", "/signup", {"username": "ravi", "password": "monsoon2026"}), ("signup again", "/signup", {"username": "ravi", "password": "another-pass"}), ("short password", "/signup", {"username": "anu", "password": "abc"}), ("login ok", "/login", {"username": "ravi", "password": "monsoon2026"}), ("wrong password", "/login", {"username": "ravi", "password": "Monsoon2026"}), ("unknown user", "/login", {"username": "nobody", "password": "monsoon2026"}), ]: r = c.post(url, json=body) print(f"{label:<15} -> {r.status_code} {r.text[:120]}")
Output
signup ravi -> 201 {"id":1,"username":"ravi"} signup again -> 409 {"detail":"Username taken"} short password -> 422 {"detail":[{"type":"string_too_short","loc":["body","password"],"msg":"String should have at least 8 characters","ctx":{ login ok -> 200 {"message":"Welcome back, ravi"} wrong password -> 401 {"detail":"Wrong username or password"} unknown user -> 401 {"detail":"Wrong username or password"}
Output - what is in the database
$ sqlite3 users.db "SELECT * FROM user;" 1|ravi|$argon2id$v=19$m=65536,t=3,p=4$85IUKbVcU/8DAKmNoW5sKQ$qdl7EzOPgMX71hzZ1xXvRQ/YAMoZQTqRC+ySyt+sJC8

Leak 1: login timing told which users exist

Our first login (accounts_v1.py) did: if user is None or not verify(...). For an unknown user, Python skipped verify. timing.py measured 20 logins each:

  • Before: wrong password for ravi 40.7 ms, unknown user 0.7 ms. The message was the same - but the time told an attacker which usernames are real.
  • The fix: always run verify. For an unknown user, check against DUMMY_HASH - a hash made at startup that matches nothing.
  • After: 43.7 ms and 39.9 ms - the difference is gone.
The first version (accounts_v1.py)
user = session.exec(select(User).where(User.username == data.username)).first() if user is None or not password_hash.verify(data.password, user.hashed_password): raise HTTPException(status_code=401, detail="Wrong username or password") # one message for both
timing.py
import importlib import statistics import sys import time from fastapi.testclient import TestClient app = importlib.import_module(sys.argv[1]).app def average_ms(client, username, tries=20): times = [] for _ in range(tries): start = time.perf_counter() client.post("/login", json={"username": username, "password": "guess-1234"}) times.append((time.perf_counter() - start) * 1000) return statistics.mean(times) with TestClient(app) as c: print(sys.argv[1]) print(f"wrong password (ravi exists): {average_ms(c, 'ravi'):.1f} ms") print(f"unknown user (nobody): {average_ms(c, 'nobody'):.1f} ms")
Output - python timing.py accounts_v1, then accounts
accounts_v1 wrong password (ravi exists): 40.7 ms unknown user (nobody): 0.7 ms accounts wrong password (ravi exists): 43.7 ms unknown user (nobody): 39.9 ms

Leak 2: the 422 echoed the password

A short password at signup gave a normal 422 - with "input" in it:

  • Before: "input":"abc" - the password went back in the response, and into any log that stores responses.
  • The fix: an exception handler for RequestValidationError (Lesson 3.2) that removes "input" from every error.
  • After: the same message, without the input.
  • Also make sure your request logs never store bodies of /signup and /login.
Output - before
{"detail":[{"type":"string_too_short","loc":["body","password"],"msg":"String should have at least 8 characters","input":"abc","ctx":{"min_length":8}}]}
Output - after
{"detail":[{"type":"string_too_short","loc":["body","password"],"msg":"String should have at least 8 characters","ctx":{"min_length":8}}]}

Upgrading old hashes

Computers get faster, so the recommended cost goes up over time. verify_and_update checks a password AND tells you when its hash uses old settings:

  • A hash made long ago with weak settings (m=8192,t=1) still verified: True.
  • verify_and_update also returned a NEW hash with today’s settings (m=65536,t=3). Save it in the user row at login.
  • At the next login it returned None - nothing to update.
  • This is the only moment you have the real password, so it is the only moment you can re-hash.
upgrade.py
from pwdlib import PasswordHash from pwdlib.hashers.argon2 import Argon2Hasher old = PasswordHash((Argon2Hasher(time_cost=1, memory_cost=8192),)) # weak settings from long ago stored = old.hash("monsoon2026") print("stored long ago:", stored[:40] + "...") current = PasswordHash.recommended() ok, new_hash = current.verify_and_update("monsoon2026", stored) # at login print("password ok: ", ok) print("new hash: ", new_hash[:40] + "..." if new_hash else None) ok, again = current.verify_and_update("monsoon2026", new_hash) print("next login: ", ok, "- new hash:", again)
Output
stored long ago: $argon2id$v=19$m=8192,t=1,p=4$yUn0Q8o4Yh... password ok: True new hash: $argon2id$v=19$m=65536,t=3,p=4$/PJ55xsZ0... next login: True - new hash: None

Password hashing at a glance

Set up

Argon2, safe settings.

from pwdlib import PasswordHash
password_hash = PasswordHash.recommended()
Signup

Store only this.

password_hash.hash(password)
Login

True or False.

password_hash.verify(password, stored)
Upgrade

Save new_hash if not None.

ok, new_hash = password_hash.verify_and_update(password, stored)
Unknown user

Same time as a wrong password.

password_hash.verify(password, user.hashed_password if user else DUMMY_HASH)

Try it yourself

The code does not change. Swap the content string and the program does something else entirely.

Install

“pip install "pwdlib[argon2]" and hash your own test password three times. Compare the salts.”

Use /docs

“Run fastapi dev accounts.py, sign up in /docs, then look in users.db with sqlite3.”

Feel the cost

“Hash with Argon2Hasher(time_cost=6) instead. How many ms per hash now?”

Count the time

“Run timing.py with tries=100. Is the difference after the fix still small?”

What usually goes wrong

Storing passwords, or encrypting them

Encryption can be undone with the key. Store a hash.

Using SHA-256 or MD5

About 2 million guesses per second, and no salt. Use Argon2 via pwdlib.

✗ hashlib.sha256(password.encode()).hexdigest()
✓ password_hash.hash(password)
Skipping verify for unknown users

0.7 ms vs 40 ms told attackers which users exist. Verify against a dummy hash.

Echoing inputs in 422 errors

"input":"abc" was the password. Remove input in a RequestValidationError handler.

Different messages for unknown user and wrong password

Use one message for both.

Practice

Write these yourself before opening anything. Getting them wrong first is most of how this sticks.

1.

Add POST /change-password with {username, old_password, new_password}: verify the old password (401 if wrong, same message for unknown users and with the dummy hash), refuse a new password equal to the old one (422), and store the new hash. Also call verify_and_update in /login and save the new hash when one is returned.

Show hint

ok, new_hash = password_hash.verify_and_update(...); if new_hash: user.hashed_password = new_hash; session.add(user); session.commit().

Key points

  • Store hashes, never passwords.
  • Password hashes must be slow and salted - Argon2 through pwdlib.
  • The same password gives a different hash each time; verify still works.
  • The hash string holds the algorithm, the cost and the salt.
  • Same message AND same time for "no such user" and "wrong password".
  • Never echo passwords in errors or logs.
  • verify_and_update re-hashes old hashes at login.

Quick check before you move on

How many guesses per second did Argon2 and SHA-256 allow?
About 23 and about 2 million.
Were the two hashes of "monsoon2026" equal?
No - each has its own random salt.
How long did an unknown user take before the fix?
0.7 ms, against 40.7 ms for a wrong password.
What did verify_and_update return on the second login?
True and None - the hash was already up to date.

Interview questions

How should passwords be stored?

With a slow, salted, memory-hard password hash (Argon2id, or bcrypt/scrypt), via a maintained library, with parameters tuned to the hardware and upgraded on login; never plain, encrypted, or with fast hashes like SHA-256.

How do you prevent user enumeration on login?

Identical responses and status codes for unknown users and wrong passwords, constant work (verify against a dummy hash), rate limiting, and the same care on signup and password-reset flows.

Quiz

  1. 1.

    Why is a salt important?

  2. 2.

    Why does DUMMY_HASH fix the timing leak?

  3. 3.

    When can you re-hash a password with new settings?

Comments

Sign in to leave a comment. Your name and photo come from Google; nothing else is shared.

Loading comments...