Description
Applying SHA-2, SHA-3 or BLAKE2 directly to passwords makes guesses cheap to check if a database, backup or log leaks. A fixed salt also lets the same calculations work across users.
Potential impact
An exposed password can grant access to the account and to other services where it was reused. An administrator’s account exposes more systems and data. Weak storage can also lead to audit findings.
Remediation
- Use a dedicated library such as argon2-cffi or passlib and benchmark costs on your production hardware. Tune time, memory and parallelism for Argon2id, or N/r/p for scrypt. For PBKDF2-HMAC-SHA256, use at least 600,000 iterations. This guide recommends a cost of 12 or higher for bcrypt.
- Generate a fresh random salt of at least 16 bytes per password and store it with the hash. If using a pepper, combine it using a vetted method and keep it in protected storage separate from the database.
- Use the library’s password verification API. When you must compare digests directly, use a constant-time comparison such as
hmac.compare_digest. - Protect online logins with minimum and maximum password lengths and a rate-limit or account-lockout policy.
Examples
Before
python
import hashlib
# Incorrect: a fast general-purpose hash (sha3_256) and a static salt
STATIC_SALT = b"NaCl-2024" # Not a separate salt for each user
def insecure_hash_password(password: str) -> str:
data = password.encode("utf-8") + STATIC_SALT
digest = hashlib.sha3_256(data).hexdigest()
return digest
# Verification repeats the hash and compares strings (possible timing leakage)
def insecure_verify_password(password: str, stored_hash: str) -> bool:
calc = insecure_hash_password(password)
return calc == stored_hash
After
python
from argon2 import PasswordHasher
from argon2.exceptions import VerifyMismatchError
# Argon2id: memory-hard hashing increases the cost of GPU attacks
ph = PasswordHasher(time_cost=3, memory_cost=64 * 1024, parallelism=2, hash_len=32)
def secure_hash_password(password: str) -> str:
# The encoded hash includes an automatically generated random salt.
return ph.hash(password)
def secure_verify_password(password: str, stored_hash: str) -> bool:
try:
return ph.verify(stored_hash, password)
except VerifyMismatchError:
return False
The example’s Argon2id PasswordHasher uses time_cost=3, 64 MiB of memory and parallelism=2. It includes the salt in its output. The verification function calls ph.verify and returns False on a password mismatch.