Every login system has to store passwords, and every year another breach shows what happens when they are stored badly: plain text, a fast hash like MD5 or SHA-256, or a salt-free scheme that falls to a GPU in hours. The right answer is a slow, salted, memory-hard password hash, and in 2026 that means Argon2id. In Python you get it from argon2-cffi directly or through pwdlib, the small modern library that the official FastAPI tutorial now uses instead of passlib. In this guide we hash and verify passwords, plug the same code into a login function, migrate old bcrypt hashes to Argon2 automatically at login, and tune the cost settings for your server. Everything was tested on Python 3.13.5 with argon2-cffi 25.1.0, pwdlib 0.3.1 and bcrypt 5.0.0, and every output block is the real output of the script above it. Salts are random, so your hashes will look different.
Why passlib code breaks in 2026
A huge number of tutorials, including many FastAPI examples, still use passlib.context.CryptContext(schemes=["bcrypt"]). passlib 1.7.4 was released in October 2020 and has not been updated since. bcrypt 5.0 (September 2025) stopped silently truncating passwords longer than 72 bytes and raises ValueError instead, and passlib's start-up self-test hashes exactly such a long string. The result is that the classic snippet fails on a fresh install, even for a three-letter password:
from passlib.context import CryptContext # passlib 1.7.4 (last release: Oct 2020)
pwd_context = CryptContext(schemes=["bcrypt"], deprecated="auto")
print(pwd_context.hash("abc"))
ValueError: password cannot be longer than 72 bytes, truncate manually if necessary (e.g. my_password[:72])
You could pin bcrypt<4.1, but that only hides the problem. A better fix is to move to a maintained library and a stronger algorithm, while still accepting the bcrypt hashes already in your database.
Why Argon2id
- Winner of the Password Hashing Competition (2015) and standardized in RFC 9106; Argon2id is the variant recommended for passwords.
- Memory-hard: each guess needs tens of megabytes of RAM, which makes GPU and ASIC cracking far more expensive than with bcrypt or PBKDF2.
- Self-describing hashes: the algorithm, version, memory, iterations, parallelism and salt are stored inside the hash string, so you can change settings later without breaking old users.
- No 72-byte limit: long passphrases are hashed in full, unlike bcrypt.
Remember that hashing is one-way. You never decrypt a password; you hash the login attempt and compare. For data you need to read back, such as API keys, use encryption instead, as shown in Encrypt and Decrypt in Python with Fernet.
Install
python -m venv .venv
source .venv/bin/activate # Windows: .venv\Scripts\activate
pip install "pwdlib[argon2,bcrypt]" # also installs argon2-cffi and bcrypt
pip show pwdlib argon2-cffi bcrypt # check the installed versions
All three packages ship prebuilt wheels for Windows, macOS and Linux. pwdlib needs Python 3.10 or newer.
Step 1: Hash and verify with argon2-cffi
PasswordHasher() uses Argon2id with the RFC 9106 low-memory profile: 64 MiB of memory, 3 iterations and 4 lanes. verify() returns True or raises VerifyMismatchError, so a wrong password can never be mistaken for a valid one.
import time
from argon2 import PasswordHasher
from argon2.exceptions import VerifyMismatchError
ph = PasswordHasher() # Argon2id, RFC 9106 low-memory profile
password = "correct horse battery staple"
t0 = time.perf_counter()
h1 = ph.hash(password)
ms = (time.perf_counter() - t0) * 1000
h2 = ph.hash(password)
print("Hash 1:", h1)
print("Hash length:", len(h1), "chars")
print(f"Hashing took {ms:.0f} ms")
print("Same password, same hash?", h1 == h2) # random salt each time
print("Right password ->", ph.verify(h1, password))
try:
ph.verify(h1, "correct horse battery stapler")
except VerifyMismatchError:
print("Wrong password -> VerifyMismatchError")
print("Needs rehash?", ph.check_needs_rehash(h1))
Hash 1: $argon2id$v=19$m=65536,t=3,p=4$TOIK6zBRgrQ4g2ArHmPJHg$I6WPDQXxiO/ktjI36BrEWdZZ5t1y3i2hbHNoh4UIxKU
Hash length: 97 chars
Hashing took 79 ms
Same password, same hash? False
Right password -> True
Wrong password -> VerifyMismatchError
Needs rehash? False
Notice the hash format: $argon2id$v=19$m=65536,t=3,p=4$, then the 16-byte salt and the 32-byte hash in base64. Hashing the same password twice gives two different strings because the salt is random, so never look users up by hash; look them up by username or e-mail and then verify. Store the full 97-character string in a VARCHAR(255) column.
Step 2: The pwdlib way (what FastAPI uses)
pwdlib wraps argon2-cffi and bcrypt behind one small API: hash(), verify() and verify_and_update(). PasswordHash.recommended() gives you Argon2id with the same safe defaults. Here it is inside the two functions every app needs:
from pwdlib import PasswordHash
password_hash = PasswordHash.recommended() # Argon2id, as in the FastAPI docs
def create_user(username: str, password: str) -> dict:
return {"username": username, "hashed_password": password_hash.hash(password)}
def login(user: dict, password: str) -> bool:
return password_hash.verify(password, user["hashed_password"])
user = create_user("ayesha", "S3cure!Passphrase-2026")
print("Stored:", user["hashed_password"][:52] + "...")
print("Login with right password:", login(user, "S3cure!Passphrase-2026"))
print("Login with wrong password:", login(user, "s3cure!passphrase-2026"))
print("Algorithm:", user["hashed_password"].split("$")[1])
Stored: $argon2id$v=19$m=65536,t=3,p=4$nOc3flyz1H5YHi8NwKR3e...
Login with right password: True
Login with wrong password: False
Algorithm: argon2id
Unlike argon2-cffi, pwdlib's verify() returns False for a wrong password instead of raising, which keeps login handlers short. Note the argument order too: pwdlib is verify(password, hash), while argon2-cffi is verify(hash, password). Mixing them up is the most common bug when switching between the two.
Step 3: Migrate old bcrypt hashes at login
You cannot convert a bcrypt hash to Argon2 offline because you do not know the passwords. The standard trick is rehash on login: keep a bcrypt hasher for verification only, and when a user logs in successfully, store a fresh Argon2 hash. List the hasher for new hashes first:
import bcrypt
from pwdlib import PasswordHash
from pwdlib.hashers.argon2 import Argon2Hasher
from pwdlib.hashers.bcrypt import BcryptHasher
# A hash created years ago by passlib/bcrypt and still sitting in your users table
old_hash = bcrypt.hashpw(b"letmein-2019", bcrypt.gensalt(rounds=12)).decode()
print("Old bcrypt hash:", old_hash)
# First hasher = used for new hashes; the others are only used to verify old ones
password_hash = PasswordHash((Argon2Hasher(), BcryptHasher()))
ok, new_hash = password_hash.verify_and_update("letmein-2019", old_hash)
print("Login OK:", ok)
print("Upgraded hash:", new_hash[:40] + "...")
ok, again = password_hash.verify_and_update("letmein-2019", new_hash)
print("Next login OK:", ok, "| needs another update:", again is not None)
print("Wrong password:", password_hash.verify_and_update("letmein-2020", old_hash))
# bcrypt only reads the first 72 bytes; bcrypt 5.0 now refuses longer input
try:
bcrypt.hashpw(("x" * 73).encode(), bcrypt.gensalt())
except ValueError as e:
print("bcrypt 73-byte password -> ValueError:", e)
Old bcrypt hash: $2b$12$swzytmW68pvk5R9Rsnh63OpS2YO7jIvqHEGebv1ERaSweCR/enCFi
Login OK: True
Upgraded hash: $argon2id$v=19$m=65536,t=3,p=4$6cOY18ROM...
Next login OK: True | needs another update: False
Wrong password: (False, None)
bcrypt 73-byte password -> ValueError: password cannot be longer than 72 bytes, truncate manually if necessary (e.g. my_password[:72])
verify_and_update() returns a tuple: whether the password is correct, and a new hash if the stored one should be replaced (or None). In a real app you write new_hash back to the user row, for example with an UPDATE users SET hashed_password = ... or through your ORM as in SQLAlchemy 2.0 ORM in Python. After a few months most active users are on Argon2, and you can force a password reset for the rest. The last line shows the bcrypt 5.0 limit: if you must keep creating bcrypt hashes, reject or pre-hash passwords longer than 72 bytes yourself.
Step 4: Tune the cost for your server
Password hashing should be slow for attackers but still fast enough for your login endpoint. Measure on your own hardware. This script compares three profiles and shows how check_needs_rehash() flags old hashes when you raise the cost:
import time
from argon2 import PasswordHasher, extract_parameters
profiles = {
"argon2-cffi default": PasswordHasher(),
"OWASP minimum": PasswordHasher(time_cost=2, memory_cost=19 * 1024, parallelism=1),
"high security": PasswordHasher(time_cost=4, memory_cost=128 * 1024, parallelism=4),
}
for name, ph in profiles.items():
t0 = time.perf_counter()
for _ in range(5):
h = ph.hash("benchmark-password")
ms = (time.perf_counter() - t0) * 1000 / 5
p = extract_parameters(h)
print(f"{name:20} t={p.time_cost} m={p.memory_cost // 1024:>3} MiB p={p.parallelism} {ms:6.1f} ms/hash")
# Raise the cost later: old hashes are flagged and re-hashed on next login
old = profiles["OWASP minimum"].hash("user-password")
print("Old hash needs rehash under default profile?", profiles["argon2-cffi default"].check_needs_rehash(old))
argon2-cffi default t=3 m= 64 MiB p=4 61.9 ms/hash
OWASP minimum t=2 m= 19 MiB p=1 20.7 ms/hash
high security t=4 m=128 MiB p=4 126.5 ms/hash
Old hash needs rehash under default profile? True
On this 8-core box the default took about 62 ms per hash, well inside the common target of 50 to 500 ms per login. The OWASP Password Storage Cheat Sheet lists m=19 MiB, t=2, p=1 as the minimum for Argon2id; use it on small containers or serverless functions where 64 MiB per login would be too much memory. Remember that memory is used per concurrent login: 20 simultaneous logins with the default profile need about 1.3 GB, so size your workers accordingly. With pwdlib, pass the same values to Argon2Hasher(time_cost=..., memory_cost=..., parallelism=...).
Using it in FastAPI
from pwdlib import PasswordHash
from pwdlib.hashers.argon2 import Argon2Hasher
from pwdlib.hashers.bcrypt import BcryptHasher
password_hash = PasswordHash((Argon2Hasher(), BcryptHasher()))
DUMMY_HASH = password_hash.hash("dummy-password") # created once at start-up
def authenticate_user(db, username: str, password: str):
user = db.get_user(username)
if user is None:
password_hash.verify(password, DUMMY_HASH) # same timing for unknown users
return None
ok, new_hash = password_hash.verify_and_update(password, user.hashed_password)
if not ok:
return None
if new_hash:
db.save_hash(user.id, new_hash) # silent upgrade
return user
We tested this function with a fake user store: a bcrypt user logged in, was silently upgraded to Argon2id, and logged in again; a wrong password and an unknown username both returned None. Verifying against it for unknown usernames makes failed logins take the same time, so attackers cannot discover which accounts exist. Plug this function into the token flow from Authentication and Authorization with FastAPI in Python and replace its passlib lines.
Quick reference
| Task | Code |
|---|---|
| Install | pip install "pwdlib[argon2,bcrypt]" |
| Hasher (pwdlib) | PasswordHash.recommended() |
| Hash | password_hash.hash(password) |
| Verify (pwdlib) | password_hash.verify(password, hash) |
| Verify (argon2-cffi) | PasswordHasher().verify(hash, password) |
| Upgrade old hashes | ok, new = password_hash.verify_and_update(password, hash) |
| Accept old bcrypt | PasswordHash((Argon2Hasher(), BcryptHasher())) |
| OWASP minimum | PasswordHasher(time_cost=2, memory_cost=19456, parallelism=1) |
| Settings changed? | ph.check_needs_rehash(hash) |
Common problems and fixes
ValueError: password cannot be longer than 72 bytesfrom passlib: passlib 1.7.4 is not compatible with bcrypt 5. Switch to pwdlib as shown above, or use the maintained forklibpassif you need passlib's API for many legacy schemes.(trapped) error reading bcrypt versionwarning: the same passlib and new bcrypt mismatch; it disappears once passlib is removed.UnknownHashErrorfrom pwdlib: the stored hash uses an algorithm none of your hashers recognise (for example a Djangopbkdf2_sha256$hash). Add the right hasher or force a password reset for those users.- Login always fails after switching libraries: check the argument order. pwdlib is
verify(password, hash); argon2-cffi isverify(hash, password). - Out-of-memory under load: lower
memory_costor limit concurrent logins; do not drop below the OWASP minimum. - Do not use
hashlib.sha256for passwords: it is designed to be fast, which is exactly what an attacker wants.
Conclusion
Modern password storage in Python takes three lines: PasswordHash.recommended(), hash() when a user signs up, and verify_and_update() when they log in. That gives you Argon2id with sensible defaults, a smooth path off passlib and bcrypt, and hashes that can be upgraded whenever you raise the cost. If your project still imports passlib, 2026 is the year to replace it.