Password Hashing

Never Store Plain Passwords

Store only a slow, salted hash of each password. In production use a dedicated library (pwdlib with Argon2, or bcrypt). The idea, shown with Python's built-in PBKDF2:

Example

import hashlib, hmac, os

def hash_password(password: str) -> str:
    salt = os.urandom(16)
    digest = hashlib.pbkdf2_hmac("sha256", password.encode(), salt, 200_000)
    return salt.hex() + ":" + digest.hex()

def verify_password(password: str, stored: str) -> bool:
    salt_hex, digest_hex = stored.split(":")
    digest = hashlib.pbkdf2_hmac("sha256", password.encode(), bytes.fromhex(salt_hex), 200_000)
    return hmac.compare_digest(digest.hex(), digest_hex)   # constant-time comparison

stored = hash_password("S3cret!pass")
print("stored length:", len(stored))
print("correct password:", verify_password("S3cret!pass", stored))
print("wrong password:", verify_password("guess123", stored))

Output

stored length: 97
correct password: True
wrong password: False