Lesson 5 of 10
Password Hashing & Salting
Password storage is one of the most critical and most frequently botched security implementations. When databases are breached (and they will be), proper password hashing is the last line of defense protecting your users' credentials.
Why Password Storage Is Difficult
# The Problem with Naive Password Storage
# WORST: Plaintext storage
stored = "password123"
# LinkedIn 2012: 6.5M plaintext passwords exposed - immediate compromise
# BAD: Unsalted MD5/SHA-1
stored = hashlib.md5("password123").hexdigest()
# = "482c811da5d5b4bc6d497ffa98491e38"
# Rainbow table attack: Pre-computed hash→password lookup tables
# Crackstation.net can reverse most common MD5 hashes instantly
# BAD: Unsalted SHA-256 (fast - billions of attempts per second on GPU)
stored = hashlib.sha256("password123").hexdigest()
# RTX 4090 GPU: ~10 billion SHA-256 hashes/second
# 8-char password cracked in minutes
# CORRECT: Use a password hashing algorithm designed for this purpose:
# - bcrypt (1999): Work factor adjustable, 72-char max, widely supported
# - Argon2 (2015): Winner of Password Hashing Competition, best modern choice
# - scrypt: Used by Litecoin, memory-hard
# Key property: SLOW BY DESIGN - makes brute force economically infeasiblebcrypt Implementation
import bcrypt
# Register: Hash password with bcrypt
def hash_password(plaintext_password: str) -> bytes:
# bcrypt auto-generates a salt and includes it in the hash output
# Cost factor 12 = 2^12 = 4096 iterations (~150ms on modern hardware)
# Each doubling of cost factor doubles crack time
salt = bcrypt.gensalt(rounds=12)
hashed = bcrypt.hashpw(plaintext_password.encode('utf-8'), salt)
return hashed
# Login: Verify password against stored hash
def verify_password(plaintext_password: str, stored_hash: bytes) -> bool:
return bcrypt.checkpw(plaintext_password.encode('utf-8'), stored_hash)
# Usage
hashed = hash_password("MySecurePassword!")
print(f"Stored hash: {hashed.decode()}")
# Output: $2b$12$LQv3c1yqBWVHxkd0LHAkCOYz6TtxMQJqhN...(salt embedded in hash)
# The $2b$12$ prefix tells you: bcrypt version 2b, cost factor 12
# The salt is embedded in the output - no need to store separately
print(verify_password("MySecurePassword!", hashed)) # True
print(verify_password("WrongPassword", hashed)) # FalseArgon2 - The Modern Standard
from argon2 import PasswordHasher
from argon2.exceptions import VerifyMismatchError
# Argon2 is the winner of the 2015 Password Hashing Competition
# Three variants: Argon2d (GPU-resistant), Argon2i (side-channel resistant), Argon2id (recommended)
ph = PasswordHasher(
time_cost=2, # Number of iterations
memory_cost=65536, # Memory usage in KiB (64 MB - defeats GPU/ASIC attacks)
parallelism=2, # Number of parallel threads
hash_len=32, # Output hash length
salt_len=16 # Salt length
)
# Hash a password
hashed = ph.hash("UserPassword123!")
print(f"Argon2id hash: {hashed[:40]}...")
# Verify password
try:
ph.verify(hashed, "UserPassword123!")
print("Password correct!")
except VerifyMismatchError:
print("Password incorrect!")
# Check if hash needs to be rehashed (if parameters were updated)
if ph.check_needs_rehash(hashed):
# Rehash with updated parameters on next successful login
new_hash = ph.hash("UserPassword123!")Password Security Best Practices
- Never store plaintext passwords - this seems obvious but breaches reveal it still happens
- Use bcrypt (rounds >= 12) or Argon2id - never MD5, SHA-1, or plain SHA-256 for passwords
- bcrypt has a 72-character limit - for passwords longer than 72 bytes, pre-hash with SHA-256 before bcrypt (or use Argon2 which has no length limit)
- Rehash on login: If you upgrade your hashing algorithm or increase cost factors, rehash passwords when users log in successfully (you have the plaintext at that moment)
- Pepper: In addition to the salt (embedded in hash), add a server-side secret (pepper) either pre-hash or as HMAC. If database is breached but server secret is not, even password hashes are useless to attackers
Common Mistakes
- Using bcrypt rounds=4 for speed - lower round counts dramatically reduce crack time; use minimum rounds=12 in production
- Implementing your own salt management - bcrypt and argon2 handle salting automatically; manual salt management introduces implementation bugs
- Storing password hashes and pepper in the same database - the pepper's value is nullified if both are compromised together; store pepper in environment variable or HSM
Tip
Tip
Practice Password Hashing Salting in small, isolated examples before integrating into larger projects. Breaking concepts into small experiments builds genuine understanding faster than reading alone.
The foundational security model: Confidentiality (privacy), Integrity (trust), and Availability (uptime).
Practice Task
Note
Practice Task - (1) Write a working example of Password Hashing Salting from scratch without looking at notes. (2) Modify it to handle an edge case (empty input, null value, or error state). (3) Share your solution in the Priygop community for feedback.
Quick Quiz
Common Mistake
Warning
A common mistake with Password Hashing Salting is skipping edge case testing - empty inputs, null values, and unexpected data types. Always validate boundary conditions to write robust, production-ready cybersecurity code.
Key Takeaways
- Password storage is one of the most critical and most frequently botched security implementations.
- Never store plaintext passwords - this seems obvious but breaches reveal it still happens
- Use bcrypt (rounds >= 12) or Argon2id - never MD5, SHA-1, or plain SHA-256 for passwords
- bcrypt has a 72-character limit - for passwords longer than 72 bytes, pre-hash with SHA-256 before bcrypt (or use Argon2 which has no length limit)
Finished this lesson?