SHA-256 won't save your passwords: salt, pepper, Argon2id and Django's automatic rehashing
Why do "hashed" passwords from a leaked table get cracked within hours? Slow hash functions, Django's PASSWORD_HASHERS, wrapping legacy hashes, brute-force limits and constant-time comparison.
Picture a database dump of a users table showing up somewhere public. Every row has a password column holding a 64-character hex string: sha256(password). The team says "it's okay, they're hashed". It isn't okay. Within hours, the most popular passwords are recovered, and the people who reused them on their email and banking apps are next.
This post is about how to store passwords so a leaked table is a nuisance, not a disaster: why a fast hash fails, what salt and pepper actually do, how PBKDF2, bcrypt, scrypt and Argon2id differ, how Django upgrades hashes on its own, and the two things around the hash that people forget: brute-force protection and constant-time comparison.
Why SHA-256 is not enough
Here is the version that still shows up in legacy code:
import hashlib
def hash_password(raw: str) -> str:
return hashlib.sha256(raw.encode()).hexdigest()
def check_password(raw: str, stored: str) -> bool:
return hash_password(raw) == stored
It has three separate problems.
It is fast. SHA-256 was designed to hash gigabytes quickly. That is great for file checksums and terrible for passwords: an attacker with the dump runs a wordlist through the same function on GPUs and compares. The faster your hash, the more guesses per second they get for free.
No salt. The same password always produces the same hash. Precomputed tables (rainbow tables) work directly, and an attacker can see at a glance which users share a password:
SELECT password, count(*) AS users
FROM legacy_users
GROUP BY password
HAVING count(*) > 1
ORDER BY users DESC
LIMIT 10;
If that query returns rows, every account in a group falls together.
Plain ==. String comparison stops at the first differing character. For password hashes this is a minor issue, but the same habit around API keys and webhook signatures is a real leak. More on that later.
Salt and pepper: what each one protects against
A salt is a random value generated per password and stored next to the hash. It is not a secret. Its only job is to make every hash unique: two users with qwerty123 get different hashes, precomputed tables become useless, and the attacker has to attack each account separately.
A pepper is one secret value for the whole system that is not stored in the database: it lives in an environment variable or a secret store. If only the database leaks, the attacker cannot even start guessing without the pepper. The cost is operational: losing the pepper means nobody can log in, and rotating it is painful because you cannot rehash a password you don't know.
Salt makes each hash unique. Slowness makes each guess expensive. Pepper helps only if the database leaks without the application secrets. You need the first two always; the third is optional.
Slow hash functions: PBKDF2, bcrypt, scrypt, Argon2id
A password hash should be deliberately expensive, with a cost you can tune upward as hardware gets faster. The four common options:
| Algorithm | Cost parameters | Memory-hard | Django hasher | Notes |
|---|---|---|---|---|
| PBKDF2-HMAC-SHA256 | iterations | no | PBKDF2PasswordHasher (default) |
Widely approved (e.g. FIPS), but cheap to parallelise on GPUs |
| bcrypt | rounds (log2) | a little (4 KiB) | BCryptSHA256PasswordHasher |
Only uses the first 72 bytes; Django prehashes with SHA-256 |
| scrypt | N, r, p | yes | ScryptPasswordHasher |
Memory ≈ 128 · N · r bytes |
| Argon2id | time, memory, parallelism | yes | Argon2PasswordHasher |
Password Hashing Competition winner (2015), OWASP's first choice |
Why memory matters: GPUs and ASICs have thousands of cores but little memory per core. PBKDF2 only burns CPU time, so an attacker parallelises it cheaply. scrypt and Argon2 force every guess to touch a large chunk of RAM, which makes massive parallel guessing far more expensive. Argon2id is the hybrid variant: it combines the side-channel resistance of Argon2i with the GPU resistance of Argon2d, and it is what Django uses.
You can read the algorithm and parameters straight out of Django's stored value:
pbkdf2_sha256$<iterations>$<salt>$<hash>
argon2$argon2id$v=19$m=102400,t=2,p=8$<salt_b64>$<hash_b64>
bcrypt_sha256$$2b$12$<salt_and_hash>
scrypt$16384$<salt>$8$5$<hash>
The format is algorithm$parameters$salt$hash. That prefix is what makes migration possible: Django knows which hasher created each row.
Django: switching to Argon2
Django ships with PBKDF2 first in PASSWORD_HASHERS. To use Argon2, install the extra dependency (argon2-cffi):
pip install "django[argon2]"
And put Argon2 first:
# settings.py
PASSWORD_HASHERS = [
"django.contrib.auth.hashers.Argon2PasswordHasher", # new hashes
"django.contrib.auth.hashers.PBKDF2PasswordHasher", # still verifies old ones
"django.contrib.auth.hashers.PBKDF2SHA1PasswordHasher",
"django.contrib.auth.hashers.BCryptSHA256PasswordHasher",
"django.contrib.auth.hashers.ScryptPasswordHasher",
]
The rule is simple: the first hasher is used for every new password, and all hashers in the list are used to verify existing ones. Do not remove old hashers while users still have hashes in that format: check_password cannot identify the algorithm and just returns False, so those users silently cannot log in.
Django's Argon2 defaults are time_cost=2, memory_cost=102400 (KiB, so 100 MiB) and parallelism=8. That is solid security, but 100 MiB per check matters when ten login requests hit one small container at once. You can tune it with a subclass that keeps the same algorithm name:
# accounts/hashers.py
from django.contrib.auth.hashers import Argon2PasswordHasher
class TunedArgon2PasswordHasher(Argon2PasswordHasher):
# algorithm stays "argon2", so existing hashes are still recognised
time_cost = 3
memory_cost = 65536 # KiB, i.e. 64 MiB per check
parallelism = 2
Put this class in place of the stock Argon2PasswordHasher line (not next to it, since both claim the name argon2). Choose parameters by measurement, not by guesswork. Run this on the same hardware as production:
# python manage.py shell
import statistics
import time
from django.contrib.auth.hashers import check_password, make_password
raw = "correct horse battery staple"
encoded = make_password(raw)
samples = []
for _ in range(20):
t0 = time.perf_counter()
check_password(raw, encoded)
samples.append(time.perf_counter() - t0)
print(encoded.split("$")[0], f"median={statistics.median(samples) * 1000:.1f} ms")
A common target is a few hundred milliseconds per check on your server: slow for an attacker running billions of guesses, invisible to a user logging in once.
Automatic rehashing: how the upgrade happens
The nice part is that you don't need a migration to move users to Argon2. Look at what AbstractBaseUser.check_password does:
# django/contrib/auth/base_user.py (simplified)
def check_password(self, raw_password):
def setter(raw_password):
self.set_password(raw_password)
self._password = None # a hash upgrade is not a password change
self.save(update_fields=["password"])
return check_password(raw_password, self.password, setter)
Inside django.contrib.auth.hashers.verify_password, Django identifies the hasher from the prefix and computes must_update: true if the stored algorithm differs from the preferred one, or if the preferred hasher's parameters have changed (PBKDF2 iterations, Argon2 time/memory/parallelism, bcrypt rounds, scrypt work factor, or a too-short salt). If the password is correct and must_update is true, the setter rehashes with the current hasher and saves only the password field.
This also explains the iteration count: Django raises the PBKDF2 default in every feature release, and after an upgrade each user is rehashed with the new count on their next successful login.
The weakness: users who never log in stay on the old hash forever. For an old PBKDF2 hash that is acceptable. For the sha256(password) column from the opening, it is not.
Upgrading legacy hashes without waiting for logins
The trick from Django's own documentation is to wrap the old hash: treat the existing sha256(password) value as the input to PBKDF2. You don't need the plaintext, and the weak hash disappears from the database immediately.
# accounts/hashers.py
import hashlib
from django.contrib.auth.hashers import PBKDF2PasswordHasher
from django.utils.encoding import force_bytes
class PBKDF2WrappedSHA256PasswordHasher(PBKDF2PasswordHasher):
"""PBKDF2 over the legacy sha256(password) value."""
algorithm = "pbkdf2_wrapped_sha256"
def encode_sha256_hash(self, sha256_hex, salt, iterations=None):
return super().encode(sha256_hex, salt, iterations)
def encode(self, password, salt, iterations=None):
sha256_hex = hashlib.sha256(force_bytes(password)).hexdigest()
return self.encode_sha256_hash(sha256_hex, salt, iterations)
A data migration that rewrites every legacy row (the regex lookup becomes PostgreSQL's ~ operator):
# accounts/migrations/0005_wrap_legacy_sha256.py
from django.db import migrations
def wrap_legacy_hashes(apps, schema_editor):
from accounts.hashers import PBKDF2WrappedSHA256PasswordHasher
User = apps.get_model("accounts", "User")
hasher = PBKDF2WrappedSHA256PasswordHasher()
legacy = User.objects.filter(password__regex=r"^[0-9a-f]{64}$")
for user in legacy.iterator(chunk_size=500):
user.password = hasher.encode_sha256_hash(user.password, hasher.salt())
user.save(update_fields=["password"])
class Migration(migrations.Migration):
dependencies = [("accounts", "0004_previous")]
operations = [
migrations.RunPython(wrap_legacy_hashes, migrations.RunPython.noop),
]
And register the hasher so Django can verify these rows:
PASSWORD_HASHERS = [
"django.contrib.auth.hashers.Argon2PasswordHasher",
"django.contrib.auth.hashers.PBKDF2PasswordHasher",
"accounts.hashers.PBKDF2WrappedSHA256PasswordHasher",
]
When such a user logs in, the algorithm pbkdf2_wrapped_sha256 differs from the preferred argon2, so the setter rehashes them to Argon2. Two cautions: each row costs one full PBKDF2 computation, so measure first and on a big table run it as a batched management command rather than inside a deploy; and since the legacy hash was unsalted, this only fixes storage, not passwords that were already exposed.
Pepper in Django, if you need it
Django has no built-in pepper, but a hasher subclass is enough. This one HMACs the password with a secret key before Argon2:
# accounts/hashers.py
import hashlib
import hmac
from django.conf import settings
from django.contrib.auth.hashers import Argon2PasswordHasher
from django.utils.encoding import force_bytes
class PepperedArgon2PasswordHasher(Argon2PasswordHasher):
algorithm = "argon2_peppered"
def _pepper(self, password):
key = force_bytes(settings.PASSWORD_PEPPER) # from env / secret store, not the DB
return hmac.new(key, force_bytes(password), hashlib.sha256).hexdigest()
def encode(self, password, salt):
return super().encode(self._pepper(password), salt)
def verify(self, password, encoded):
return super().verify(self._pepper(password), encoded)
Use a new algorithm name (argon2_peppered), put it first in PASSWORD_HASHERS, and existing argon2 hashes migrate on login like any other upgrade. Treat PASSWORD_PEPPER like a database encryption key: backed up, never in the repository, never rotated casually.
Brute-force protection: the hash is not enough
A slow hash protects a stolen database. It does nothing for the live login endpoint, where an attacker simply submits guesses. And worse: an expensive hash makes every login request expensive, so an unprotected endpoint is also a cheap way to load your CPU and memory.
Django itself does not limit login attempts. Packages such as django-axes exist; here is a small version on top of the Redis cache so the mechanism is visible:
# accounts/throttle.py
from django.core.cache import cache
USER_LIMIT = 5 # failed attempts per username
IP_LIMIT = 50 # failed attempts per IP
WINDOW = 15 * 60 # seconds
def _keys(username: str, ip: str) -> tuple[str, str]:
return f"login:fail:u:{username.casefold()}", f"login:fail:ip:{ip}"
def is_throttled(username: str, ip: str) -> bool:
user_key, ip_key = _keys(username, ip)
counts = cache.get_many([user_key, ip_key])
return counts.get(user_key, 0) >= USER_LIMIT or counts.get(ip_key, 0) >= IP_LIMIT
def register_failure(username: str, ip: str) -> None:
for key in _keys(username, ip):
cache.add(key, 0, timeout=WINDOW) # sets TTL only if the key is missing
try:
cache.incr(key) # atomic INCR in Redis, TTL is kept
except ValueError: # expired between add() and incr()
cache.set(key, 1, timeout=WINDOW)
def reset_user(username: str, ip: str) -> None:
cache.delete(_keys(username, ip)[0])
# accounts/views.py
from django.contrib.auth import authenticate, login
from django.http import JsonResponse
from django.views.decorators.debug import sensitive_post_parameters
from django.views.decorators.http import require_POST
from .throttle import is_throttled, register_failure, reset_user
@sensitive_post_parameters("password")
@require_POST
def login_view(request):
username = request.POST.get("username", "")
password = request.POST.get("password", "")
ip = request.META["REMOTE_ADDR"] # behind a proxy: read it from a trusted header
if not username or not password or len(password) > 256:
return JsonResponse({"detail": "Invalid request."}, status=400)
# check the limit BEFORE the expensive hash
if is_throttled(username, ip):
return JsonResponse({"detail": "Too many attempts, try later."}, status=429)
user = authenticate(request, username=username, password=password)
if user is None:
register_failure(username, ip)
return JsonResponse({"detail": "Invalid username or password."}, status=401)
reset_user(username, ip)
login(request, user)
return JsonResponse({"ok": True})
Key decisions in this code:
- Check the limit before hashing. A throttled request costs a Redis lookup, not 100 MiB of Argon2.
- Two counters. Per username stops guessing one account; per IP stops spraying one common password across many accounts.
- Temporary throttling, not permanent lockout. If five wrong attempts lock the account until support unlocks it, anyone can lock out any user they know the username of. A window that expires is safer.
- Same error for "no such user" and "wrong password". Otherwise the endpoint itself becomes a user enumeration tool.
Constant-time comparison
== on strings returns as soon as it finds a difference, so the response time depends on how many leading bytes match. With enough measurements an attacker can recover a secret byte by byte. For anything secret that you compare directly (API keys, HMAC signatures from payment webhooks, reset tokens), use a constant-time function:
from django.utils.crypto import constant_time_compare
signature = request.headers.get("X-Signature", "")
# Wrong: == returns as soon as the first byte differs
if signature == expected_signature:
...
# Right: time does not depend on where the strings differ
if constant_time_compare(signature, expected_signature):
...
hmac.compare_digest from the standard library does the same; note that it accepts str only if both are ASCII, while constant_time_compare converts to bytes first. Django's own hashers already use constant_time_compare internally.
There is a second timing leak: user enumeration. If your custom backend returns immediately when the user does not exist, "unknown phone" answers in a millisecond and "wrong password" in hundreds. Django's ModelBackend runs the default hasher once in that case; a custom backend must do the same:
# accounts/backends.py
from django.contrib.auth import get_user_model
from django.contrib.auth.backends import ModelBackend
class PhoneBackend(ModelBackend):
def authenticate(self, request, phone=None, password=None, **kwargs):
UserModel = get_user_model()
if phone is None or password is None:
return None
try:
user = UserModel._default_manager.get(phone=phone)
except UserModel.DoesNotExist:
# Wrong would be a bare `return None`: a fast answer reveals
# that the phone is not registered. Do the same hashing work.
UserModel().set_password(password)
return None
if user.check_password(password) and self.user_can_authenticate(user):
return user
return None
Pitfalls I see in production
- Removing a hasher too early. Users whose hashes use it can no longer log in, and nothing logs an error. Check which prefixes are still in the table first:
SELECT split_part(password, '$', 1), count(*) FROM accounts_user GROUP BY 1;. - Argon2 memory under load.
memory_costis per verification. Many concurrent logins multiply it. Size workers and limits accordingly, and keep the rate limit in front. - Comparing with
make_password.make_password(raw) == user.passwordis always false because the salt is random. Usecheck_password. - Slow test suite. Every
create_userruns the real hasher. In test settings use a fast one:
# settings/test.py
PASSWORD_HASHERS = ["django.contrib.auth.hashers.MD5PasswordHasher"]
- Passwords in logs. Error reports can include POST data.
sensitive_post_parametershides the field; also check your own logging and APM middleware. - Unbounded input. Put a reasonable maximum length on the password field so nobody sends megabytes into your hasher.
- Trusting
X-Forwarded-Forblindly. If anyone can set it, the per-IP limit is useless. Read the client IP only from a header your proxy sets.
Checklist
- Argon2id first in
PASSWORD_HASHERS, parameters chosen by measuring on production hardware. - Old hashers stay in the list until no rows use them.
- Legacy fast hashes wrapped with a data migration, not left waiting for logins.
- Pepper only if you can manage the secret properly.
- Login rate limit per username and per IP, checked before hashing, expiring rather than permanent.
- One error message for unknown user and wrong password; custom backends burn the same hashing time.
constant_time_comparefor every secret comparison.- Fast hasher in test settings,
sensitive_post_parameterson login views.
Takeaway
A password table will leak one day, so design for that day: unique salt per password, a deliberately slow memory-hard function like Argon2id, and parameters you revisit. Django already does the hard parts, including verifying old formats and rehashing on login, as long as you configure PASSWORD_HASHERS correctly. What it leaves to you is the live endpoint: rate limits, uniform errors and constant-time comparisons.
// comments
Loading comments...