Storing Passwords Safely in Python with Argon2id or bcrypt
If your application has user accounts, sooner or later its database may be copied by someone who should not have it. How you stored the passwords decides what happens next: whether the attacker gets every user's password (which many people reuse elsewhere), or a pile of values that are expensive to guess one at a time. This page explains the rule and shows working Python code for it.
The rule, from the OWASP Password Storage Cheat Sheet: store passwords only with a slow, salted password-hashing function. Use Argon2id; if it is not available, scrypt; bcrypt for legacy systems; PBKDF2 where FIPS-140 compliance is required.
Examples use Python 3.10 or later with argon2-cffi 25.1 and bcrypt 5.0, and were tested with Python 3.12 and pytest.
What not to do, and why
- Plain text: one leak exposes everyone.
- Encryption: anything that can be decrypted can be decrypted by whoever gets the key, and the key usually lives on the same server. Passwords never need to be read back, only checked.
- Base64 or any encoding: reversible by anyone, so it is plain text with extra steps (Base64 explained).
- MD5, SHA-1 or SHA-256 on their own: these are one-way, but they are built to be fast. An attacker with a stolen database can test enormous numbers of guesses per second against them on ordinary hardware, and common passwords fall almost immediately. Without a salt it is worse: identical passwords give identical hashes, so guessing one reveals them all.
A salt is a random value generated for each password and stored alongside the hash, so two users with the same password get different hashes and precomputed tables are useless. A slow function (one that deliberately costs time and memory per guess) turns each guess from almost free into something expensive. Password-hashing functions do both, and the libraries below handle the salt for you.
Argon2id with argon2-cffi
Install the library in a virtual environment (check the name: argon2-cffi):
python -m venv .venv
source .venv/bin/activate # Windows: .venv\Scripts\activate
python -m pip install argon2-cffi
Then a small, complete account system. It keeps users in SQLite, reads the password with getpass so it is not shown on screen, and never prints or logs it:
import getpass
import sqlite3
from argon2 import PasswordHasher
from argon2.exceptions import InvalidHashError, VerificationError
ph = PasswordHasher() # Argon2id; defaults exceed the OWASP minimums
def create_user(db, username, password):
if not 3 <= len(username) <= 64:
raise ValueError("username must be 3 to 64 characters")
if len(password) < 8:
raise ValueError("password must be at least 8 characters")
db.execute(
"INSERT INTO users (username, password_hash) VALUES (?, ?)",
(username, ph.hash(password)), # a new random salt every time
)
db.commit()
def login(db, username, password):
row = db.execute(
"SELECT id, password_hash FROM users WHERE username = ?", (username,)
).fetchone()
if row is None:
return False
user_id, stored = row
try:
ph.verify(stored, password) # constant-time comparison inside
except (VerificationError, InvalidHashError):
return False
if ph.check_needs_rehash(stored): # parameters were raised since
db.execute(
"UPDATE users SET password_hash = ? WHERE id = ?",
(ph.hash(password), user_id),
)
db.commit()
return True
if __name__ == "__main__":
db = sqlite3.connect("users.db")
db.execute(
"CREATE TABLE IF NOT EXISTS users ("
"id INTEGER PRIMARY KEY, username TEXT UNIQUE NOT NULL, "
"password_hash TEXT NOT NULL)"
)
username = input("Username: ").strip()
password = getpass.getpass("Password: ") # typed without echo
exists = db.execute(
"SELECT 1 FROM users WHERE username = ?", (username,)
).fetchone()
if exists:
print("Login ok" if login(db, username, password)
else "Invalid username or password")
else:
create_user(db, username, password)
print("Account created")
A session in the terminal (the password is typed but not displayed):
$ python accounts.py
Username: ada
Password:
Account created
$ python accounts.py
Username: ada
Password:
Login ok
$ sqlite3 users.db "SELECT username, password_hash FROM users"
ada|$argon2id$v=19$m=65536,t=3,p=4$EU81yJmQbUZsh5X5aMTxVg$lIptXEyvnnB5qpQ2O52LRFuChTk0kCZo5tGF9J6nCQc
Reading the stored hash
The stored value is a single self-describing string:
argon2id: the algorithm variant.v=19: the Argon2 version.m=65536,t=3,p=4: memory in KiB (64 MiB), iterations, and parallel lanes. These areargon2-cffi's defaults, the RFC 9106 low-memory profile.- Then the random salt and the hash, both Base64.
Because the parameters travel with the hash, verify knows how to check old hashes after you change settings, and check_needs_rehash tells you when a hash was made with weaker settings than you now use. The code above upgrades it at the next successful login, which is the only moment you have the plain password.
The OWASP cheat sheet gives minimum Argon2id settings of 19 MiB of memory, 2 iterations and 1 degree of parallelism (or one of its listed equivalent trade-offs). The library defaults are well above that. Raise or lower them so that one hash takes an acceptable time on your server, keeping in mind that each concurrent login uses that much memory.
Details the example gets right
ph.verifydoes the comparison. Do not hash the attempt yourself and compare strings: the library's verify function compares in constant time and reads the salt and parameters from the stored string.- One message for every failure. "Invalid username or password" does not tell an attacker which usernames exist.
- Parameterized SQL. The username goes into the query as a
?parameter, never by string formatting; see SQL injection and parameterized queries. - Input checked at the boundary: username length and a minimum password length. Allow long passphrases; there is no reason to cap Argon2 input at a small size.
- No password in output, logs or exceptions. Be careful with debug logging of request bodies, which is a common way passwords end up in log files.
bcrypt
bcrypt is older but still acceptable, and you will meet it in existing systems. Install bcrypt, then:
import bcrypt
def hash_password(password: str) -> bytes:
data = password.encode("utf-8")
if len(data) > 72: # bcrypt only uses the first 72 bytes
raise ValueError("password is too long (72 bytes maximum)")
return bcrypt.hashpw(data, bcrypt.gensalt()) # work factor 12 by default
def check_password(password: str, stored: bytes) -> bool:
data = password.encode("utf-8")
if len(data) > 72:
return False
return bcrypt.checkpw(data, stored)
Its hashes look like $2b$12$ followed by the salt and hash; 12 is the work factor (the library default). OWASP sets a minimum of 10. The important limit: bcrypt uses only the first 72 bytes of a password. Older versions of the Python library silently ignored the rest; since version 5.0, hashpw raises ValueError: password cannot be longer than 72 bytes. The code above rejects longer passwords with a clear message. Note that 72 bytes can be far fewer than 72 characters: "é" is two bytes in UTF-8, so 37 of them are too long. Avoid working around the limit by hashing the password with SHA-256 first; the OWASP cheat sheet explains why pre-hashing is risky. If long passphrases matter to you, use Argon2id.
scrypt and PBKDF2
Both are in Python's standard library as hashlib.scrypt and hashlib.pbkdf2_hmac, but you must then generate the salt, choose the parameters, store everything and compare in constant time yourself, so prefer a dedicated library where you can. The OWASP cheat sheet's current figures are N=2^17, r=8, p=1 for scrypt, and 600,000 iterations for PBKDF2-HMAC-SHA256.
Common mistakes
- Using a general-purpose hash (
hashlib.sha256) for passwords because it "is secure". It is secure for checksums, not for passwords; hash functions and checksums explains the difference. - Generating one salt for the whole application instead of one per password.
- Comparing hashes with
==instead of the library's verify function. - Printing the password while debugging and forgetting to remove it.
- Reaching for a general text hashing tool. The site's Hash Generator computes fast hashes (MD5 to SHA-512) for checking data; it is not for hashing passwords you will store.
Storing passwords correctly limits the damage of a breach; it does not prevent one. Rate-limit login attempts and offer multi-factor authentication as well.