IC Improve Code Recipes

Recipe 7.1 · Python

Password Hashing with PBKDF2

The Python listings are conversions of the book's C# code to Python 3.12. Each file's header says what it needs to run. The explanations were written for the C# version, so some names in the text refer to .NET.

Problem

Passwords are stored in plain text, encrypted with a reversible key, or hashed with a fast algorithm such as MD5 or SHA-1, often without a salt. When the database leaks (a backup on a file share, a developer's copy, a SQL injection), every password can be recovered in hours with commodity hardware, and many of your users reuse them elsewhere.

The way it's often written

Anti-pattern: shown so you can recognize it. Don't copy this one.

Requirements: Python 3.12+. Standard library only, nothing to install.

Python Unsalted MD5 password hashing (p140_r7_1_md5_password_hash_before.py)
"""Unsalted MD5 password hashing

Source: ImproveCode, Chapter 7, Recipe 7.1 "Password Hashing with PBKDF2"
Section: The way it's often written
Book page: 140  -- original C# listing
Converted from C# to Python.
ANTI-PATTERN: kept deliberately faithful to the C# 'not to copy' example; do not use.
hashlib.md5 stands in for MD5.Create(); hexdigest().upper() matches
BitConverter.ToString(...).Replace("-", "").
"""

import hashlib


# Not this: fast, unsalted, and broken for passwords.
def hash_password(password: str) -> str:
    return hashlib.md5(password.encode("utf-8")).hexdigest().upper()


def check(password: str, stored: str) -> bool:
    return hash_password(password) == stored

The improved recipe

Use PBKDF2 with HMAC-SHA-256, a random salt per password, a high iteration count and a self-describing storage format. Compare in constant time, and tell the caller when a stored hash should be upgraded.

If you already use ASP.NET Core Identity, or want a hasher maintained by Microsoft, use its PasswordHasher<TUser> from the Microsoft.Extensions.Identity.Core package. It works without the rest of Identity:

Register it once, as a usage snippet:

Requirements: Python 3.12+. Standard library only, nothing to install.

Python PBKDF2-SHA256 password hasher with self-describing hash format (p140_r7_1_pbkdf2_password_hasher.py)
"""PBKDF2-SHA256 password hasher with self-describing hash format

Source: ImproveCode, Chapter 7, Recipe 7.1 "Password Hashing with PBKDF2"
Section: The improved recipe
Book page: 140-141  -- original C# listing
Converted from C# to Python.
hashlib.pbkdf2_hmac replaces Rfc2898DeriveBytes.Pbkdf2, secrets.token_bytes
replaces RandomNumberGenerator, hmac.compare_digest replaces FixedTimeEquals.
"""

import base64
import binascii
import hashlib
import hmac
import secrets
from enum import Enum, auto


class PasswordVerification(Enum):
    FAILED = auto()
    SUCCESS = auto()
    SUCCESS_REHASH_NEEDED = auto()


class Pbkdf2PasswordHasher:
    _SCHEME = "pbkdf2-sha256"
    _SALT_SIZE = 16       # 128 bits
    _HASH_SIZE = 32       # 256 bits
    _ITERATIONS = 600_000
    _ALGORITHM = "sha256"

    @classmethod
    def hash(cls, password: str) -> str:
        """Returns "pbkdf2-sha256$iterations$salt$hash"."""
        if not password:
            raise ValueError("password must not be null or empty")

        salt = secrets.token_bytes(cls._SALT_SIZE)
        digest = hashlib.pbkdf2_hmac(
            cls._ALGORITHM, password.encode("utf-8"), salt,
            cls._ITERATIONS, cls._HASH_SIZE)

        return "$".join((
            cls._SCHEME,
            str(cls._ITERATIONS),
            base64.b64encode(salt).decode("ascii"),
            base64.b64encode(digest).decode("ascii"),
        ))

    @classmethod
    def verify(cls, password: str, stored_hash: str) -> PasswordVerification:
        if password is None:
            raise TypeError("password")
        if stored_hash is None:
            raise TypeError("stored_hash")

        parts = stored_hash.split("$")
        if (len(parts) != 4 or parts[0] != cls._SCHEME
                or not parts[1].isascii() or not parts[1].isdigit()
                or int(parts[1]) < 1):
            return PasswordVerification.FAILED
        iterations = int(parts[1])

        try:
            salt = base64.b64decode(parts[2], validate=True)
            expected = base64.b64decode(parts[3], validate=True)
        except (binascii.Error, ValueError):
            return PasswordVerification.FAILED

        actual = hashlib.pbkdf2_hmac(
            cls._ALGORITHM, password.encode("utf-8"), salt,
            iterations, len(expected))

        if not hmac.compare_digest(actual, expected):
            return PasswordVerification.FAILED

        return (PasswordVerification.SUCCESS_REHASH_NEEDED
                if iterations < cls._ITERATIONS
                else PasswordVerification.SUCCESS)

Requirements: Python 3.12+. Standard library only, nothing to install.

Python User password service that upgrades stale hashes on login (p141_r7_1_user_passwords_rehash_on_verify.py)
"""User password service that upgrades stale hashes on login

Source: ImproveCode, Chapter 7, Recipe 7.1 "Password Hashing with PBKDF2"
Section: The improved recipe
Book page: 141-142  -- original C# listing
Converted from C# to Python.
ASP.NET Core Identity's IPasswordHasher<T> becomes a Protocol; passlib's
CryptContext (needs_update / verify) is the usual concrete implementation.
"""

from dataclasses import dataclass
from enum import Enum, auto
from typing import Protocol


class PasswordVerificationResult(Enum):
    FAILED = auto()
    SUCCESS = auto()
    SUCCESS_REHASH_NEEDED = auto()


@dataclass
class AppUser:
    user_name: str = ""
    password_hash: str = ""


class PasswordHasher(Protocol):
    def hash_password(self, user: AppUser, password: str) -> str: ...

    def verify_hashed_password(
        self, user: AppUser, hashed_password: str, provided_password: str
    ) -> PasswordVerificationResult: ...


class UserPasswords:
    def __init__(self, hasher: PasswordHasher) -> None:
        self._hasher = hasher

    def set_password(self, user: AppUser, password: str) -> None:
        user.password_hash = self._hasher.hash_password(user, password)

    def verify(self, user: AppUser, password: str) -> bool:
        """Returns True when the password is correct. Upgrades the stored
        hash when the hasher asks for it; the caller saves the user
        afterwards."""
        result = self._hasher.verify_hashed_password(
            user, user.password_hash, password)

        if result is PasswordVerificationResult.SUCCESS_REHASH_NEEDED:
            self.set_password(user, password)

        return result is not PasswordVerificationResult.FAILED

Requirements: Python 3.12+. Install: pip install passlib

Python Registering the password hasher and UserPasswords as singletons (p142_r7_1_register_password_services.py)
"""Registering the password hasher and UserPasswords as singletons

Source: ImproveCode, Chapter 7, Recipe 7.1 "Password Hashing with PBKDF2"
Section: The improved recipe
Book page: 142  -- original C# listing
Converted from C# to Python.
ASP.NET Core DI singletons become module-level instances exposed through
FastAPI dependency functions; passlib's CryptContext plays PasswordHasher<T>.
"""

from functools import lru_cache
from typing import Any


@lru_cache(maxsize=1)
def get_password_hasher() -> Any:
    # Equivalent of AddSingleton<IPasswordHasher<AppUser>, PasswordHasher<AppUser>>()
    from passlib.context import CryptContext
    return CryptContext(schemes=["pbkdf2_sha256"], deprecated="auto")


@lru_cache(maxsize=1)
def get_user_passwords() -> Any:
    # Equivalent of AddSingleton<UserPasswords>()
    from p141_r7_1_user_passwords_rehash_on_verify import UserPasswords
    return UserPasswords(get_password_hasher())

How it works

PBKDF2 runs HMAC-SHA-256 hundreds of thousands of times. That costs a fraction of a second for one login, which nobody notices, and makes each guess in an offline attack equally expensive. The 600,000 iterations follow current OWASP guidance for PBKDF2-HMAC-SHA-256. MD5, by contrast, can be computed billions of times per second on one graphics card.

The random salt makes every stored hash unique, even for two users with the same password, so precomputed tables are useless and each account must be attacked separately.

The storage string records the scheme, iteration count, salt and hash. That is what makes the format upgradeable. When you raise Iterations next year, existing hashes still verify with the count they were created with, Verify returns SuccessRehashNeeded, and the login code stores a fresh hash while it has the plain password in hand. Over a few months the whole user table moves to the new cost without a forced reset.

CryptographicOperations.FixedTimeEquals compares every byte regardless of where the first difference is. A normal == or SequenceEqual returns early, which in principle leaks how much of the hash matched through timing.

The Identity hasher does the same job with its own versioned format (PBKDF2 with HMAC-SHA-512 and 100,000 iterations by default since .NET 7, configurable through PasswordHasherOptions). It also returns SuccessRehashNeeded, so the upgrade path is identical.

Variations and pitfalls

  • Migrating from MD5 or SHA-1: don't wait for users to log in. Wrap each old hash immediately by computing Pbkdf2(oldHash) and storing it with a different scheme name, then replace it with a normal hash at the next successful login. The weak hashes are gone from the database on day one.
  • Argon2id is the other strong choice, through a third-party package. PBKDF2 is in the base class library, FIPS-approved and good enough when the iteration count is high.
  • Hashing is CPU-heavy by design. Rate-limit login attempts (ASP.NET Core's rate-limiting middleware does this), or an attacker can use your login page to burn your CPU.
  • Never log the password, even on failure, and never return different errors for "unknown user" and "wrong password."
  • The column needs room. The PBKDF2 string here is under 100 characters; NVARCHAR(256) leaves space for future schemes.