Password Storage and Authentication
bcrypt, Argon2id, salting, work factors, and secure credential handling
Skills taught: crypto.passwords
Why Fast Hash Algorithms Are Dangerous for Passwords
Passwords must never be stored in plaintext or with fast hash functions like MD5 or SHA-256. These produce a hash in microseconds. An RTX 4090 GPU can test 184 billion MD5 hashes per second — an 8-character password falls in seconds. Purpose-built password hashing algorithms are intentionally slow.
SHA-256 vs Argon2id for Passwords
- SHA-256 (WRONG for passwords): General-purpose hash — fast by design
- Argon2id (CORRECT for passwords): Password hashing — slow and memory-intensive by design
- Salt
- A unique random value added to each password before hashing. Prevents precomputed rainbow table attacks: even if two users have the same password, their hashes are different.
- Work Factor / Cost
- A parameter that controls how slow the hash is. Increasing it by 1 doubles the work. Set it so hashing takes 100-500ms on your hardware. Increase it as hardware gets faster.
Argon2id Implementation
from argon2 import PasswordHasher
from argon2.exceptions import VerifyMismatchError, VerificationError
# --- Configure Argon2id (OWASP 2024 recommendations) ---
ph = PasswordHasher(
time_cost=3, # iterations (higher = slower)
memory_cost=65536, # 64 MB RAM required per hash (limits GPU attacks)
parallelism=4, # threads
hash_len=32, # output hash length
salt_len=16, # salt length (auto-generated)
)
# --- Hash at registration ---
password = "user_password_here"
hash_string = ph.hash(password)
print(hash_string)
# $argon2id$v=19$m=65536,t=3,p=4lt;salt>lt;hash>
# The hash string contains: algorithm, params, salt, hash — all in one
# --- Verify at login ---
try:
ph.verify(hash_string, password)
print("Password valid")
# Upgrade outdated hash parameters if needed
if ph.check_needs_rehash(hash_string):
new_hash = ph.hash(password)
# Save new_hash to DB
except VerifyMismatchError:
print("Wrong password")
except VerificationError as e:
print("Verification error:", e)
bcrypt: The Classic Fallback
import bcrypt
# --- Hash password (bcrypt handles salt automatically) ---
password = b"user_password" # must be bytes
cost = 12 # 2^12 = 4096 rounds; adjust until hash takes ~100ms
hash_bytes = bcrypt.hashpw(password, bcrypt.gensalt(rounds=cost))
print(hash_bytes) # b'$2b$12lt;22-char-salt><31-char-hash>'
# --- Verify ---
if bcrypt.checkpw(password, hash_bytes):
print("Valid")
else:
print("Invalid")
# --- IMPORTANT: bcrypt truncates at 72 bytes ---
# If password > 72 bytes, all bytes beyond 72 are ignored!
# Mitigation: SHA-256 the password first, then bcrypt
import hashlib, base64
def hash_password_safe(password: str) -> bytes:
# SHA-256 first to handle long passwords, then bcrypt
prehash = base64.b64encode(hashlib.sha256(password.encode()).digest())
return bcrypt.hashpw(prehash, bcrypt.gensalt(rounds=12))
Warning: bcrypt silently truncates passwords at 72 bytes. If a user's password is 73+ characters, bcrypt treats it the same as the first 72 bytes. For long password support, pre-hash with SHA-256 before bcrypt, or switch to Argon2id which has no length limit.
Secure Login Flow
from argon2 import PasswordHasher
from argon2.exceptions import VerifyMismatchError
import hmac
ph = PasswordHasher(time_cost=3, memory_cost=65536, parallelism=4)
# --- Registration ---
def register_user(username: str, password: str, db) -> None:
if len(password) < 12:
raise ValueError("Password too short")
hashed = ph.hash(password)
db.execute("INSERT INTO users (username, password_hash) VALUES (?, ?)",
(username, hashed))
# --- Login ---
def login_user(username: str, password: str, db) -> bool:
row = db.execute("SELECT password_hash FROM users WHERE username = ?",
(username,)).fetchone()
if not row:
# Still hash to prevent timing-based username enumeration
ph.hash("dummy_to_prevent_timing")
return False
try:
ph.verify(row["password_hash"], password)
# Transparently upgrade hash if params are outdated
if ph.check_needs_rehash(row["password_hash"]):
db.execute("UPDATE users SET password_hash = ? WHERE username = ?",
(ph.hash(password), username))
return True
except VerifyMismatchError:
return False
Tip: Always hash a dummy password on failed username lookups to prevent timing-based username enumeration. If the lookup is instant for unknown users (no DB hit) but slow for known users (bcrypt runs), an attacker can enumerate valid usernames by measuring response times.
Frequently Asked Questions
Should I add my own salt to Argon2 or bcrypt?
No. Argon2 and bcrypt include automatic, cryptographically secure salt generation. The salt is embedded in the hash output string. Adding your own salt on top provides no benefit and may introduce bugs.
How do I migrate from MD5/SHA-1 password hashes?
On next login: verify the old hash, re-hash the plaintext password with Argon2id, store the new hash, delete the old one. Mark a column to track which hashes have been upgraded. For accounts that never log in again, force password reset on their next login attempt.
What is pepper?
An application-wide secret value added to all passwords before hashing (in addition to the per-user salt). The pepper is stored outside the database (e.g., in an env var or KMS). Even if the database is breached, attackers cannot crack passwords without the pepper.