IC Improve Code Recipes

Recipe 7.4 · Python

Secure Random Tokens

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

Password-reset links, e-mail confirmation codes, API keys and one-time download links need values nobody can guess. Legacy code uses new Random(), Guid.NewGuid() or a timestamp, and stores the token in plain text, so anyone who can read the table can reset any password.

The way it's often written

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

Requirements: Python 3.12+. Install: pip install pyodbc · Needs at run time: SQL Server + Microsoft ODBC Driver 18 for SQL Server. The module loads without them; calling the code does not work without them.

Python Predictable codes and reset tokens stored in plain text (p150_r7_4_predictable_reset_token_before.py)
"""Predictable codes and reset tokens stored in plain text

Source: ImproveCode, Chapter 7, Recipe 7.4 "Secure Random Tokens"
Section: The way it's often written
Book page: 150  -- original C# listing
Converted from C# to Python.
ANTI-PATTERN: kept deliberately faithful to the C# 'not to copy' example; do not use.
random.randint stands in for System.Random, uuid4().hex for Guid "N", pyodbc for Dapper.
"""

import random
import uuid

import pyodbc


def issue_reset(db: pyodbc.Connection, user_id: int) -> str:
    # Not this: predictable values, stored as-is.
    rng = random.Random()
    code = str(rng.randint(100000, 999998))

    reset_token = uuid.uuid4().hex
    db.execute("UPDATE dbo.AppUser SET ResetToken = ? WHERE Id = ?",
               reset_token, user_id)
    db.commit()
    return code

The improved recipe

Generate tokens with RandomNumberGenerator, encode them URL-safely, store only a SHA-256 hash with an expiry, and compare hashes in constant time.

Usage for a password reset, as a sketch:

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

Python Cryptographically secure tokens, numeric codes and hashed storage (p151_r7_4_secure_tokens_hashed_storage.py)
"""Cryptographically secure tokens, numeric codes and hashed storage

Source: ImproveCode, Chapter 7, Recipe 7.4 "Secure Random Tokens"
Section: The improved recipe
Book page: 151-152  -- original C# listing
Converted from C# to Python.
secrets replaces RandomNumberGenerator (token_urlsafe for base64url,
secrets.choice for GetString); hmac.compare_digest replaces FixedTimeEquals.
"""

import base64
import hashlib
import hmac
import secrets


class SecureTokens:
    _DIGITS = "0123456789"

    @staticmethod
    def create(byte_length: int = 32) -> str:
        """URL-safe token with byte_length bytes of entropy
        (32 bytes = 256 bits = 43 characters)."""
        if byte_length < 16:
            raise ValueError("byte_length must be at least 16")
        return SecureTokens._to_base64_url(secrets.token_bytes(byte_length))

    @staticmethod
    def numeric_code(digits: int = 6) -> str:
        """Numeric code for SMS or e-mail. Short-lived and rate-limited use only."""
        if digits < 6 or digits > 10:
            raise ValueError("digits must be between 6 and 10")
        return "".join(secrets.choice(SecureTokens._DIGITS) for _ in range(digits))

    @staticmethod
    def hash_for_storage(token: str) -> str:
        """Hash to store in the database instead of the token itself."""
        if not token:
            raise ValueError("token must not be null or empty")
        return hashlib.sha256(token.encode("utf-8")).hexdigest().upper()

    @staticmethod
    def matches(token: str, stored_hash: str) -> bool:
        if not token or len(stored_hash) != 64:
            return False

        actual = hashlib.sha256(token.encode("utf-8")).digest()
        try:
            expected = bytes.fromhex(stored_hash)
        except ValueError:
            return False

        return hmac.compare_digest(actual, expected)

    @staticmethod
    def _to_base64_url(data: bytes) -> str:
        return base64.urlsafe_b64encode(data).decode("ascii").rstrip("=")

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

Python Issuing a password-reset link and storing only the token hash (p152_r7_4_password_reset_link_usage.py)
"""Issuing a password-reset link and storing only the token hash

Source: ImproveCode, Chapter 7, Recipe 7.4 "Secure Random Tokens"
Section: The improved recipe
Book page: 152  -- original C# listing
Converted from C# to Python.
Usage fragment wrapped in an async function; the PasswordReset record is a
frozen dataclass and the reset repository a Protocol.
"""

from dataclasses import dataclass
from datetime import datetime, timedelta, timezone
from typing import Protocol

from p151_r7_4_secure_tokens_hashed_storage import SecureTokens


@dataclass(frozen=True)
class PasswordReset:
    user_id: int
    token_hash: str
    expires_utc: datetime


class ResetStore(Protocol):
    async def save_async(self, reset: PasswordReset) -> None: ...


async def send_reset(resets: ResetStore, user_id: int) -> str:
    token = SecureTokens.create()
    await resets.save_async(PasswordReset(
        user_id=user_id,
        token_hash=SecureTokens.hash_for_storage(token),
        expires_utc=datetime.now(timezone.utc) + timedelta(minutes=30)))

    link = f"https://app.example.com/reset?token={token}"
    return link

How it works

RandomNumberGenerator draws from the operating system's cryptographic generator. Random is a fast pseudo-random generator meant for simulations; its output can be predicted from a few samples, and older .NET versions seeded it from the clock, so two servers starting together could produce the same sequence. A GUID is unique but not designed to be unpredictable, and version 4 GUIDs carry only 122 random bits in a recognizable format.

Thirty-two random bytes give 256 bits of entropy, far beyond any brute-force attempt. Base64url encoding swaps + and / for - and _ and drops padding, so the token can go into a URL or a file name without escaping.

RandomNumberGenerator.GetString (new in .NET 8) picks each character uniformly from the choices. The common shortcut GetInt32() % 1000000 is close, but home-made modulo arithmetic is where bias creeps in, and the built-in method removes the question.

Storing SHA256(token) instead of the token means a leaked table or a curious administrator can't use the outstanding reset links. A plain SHA-256 is enough here, unlike passwords, because the token has 256 bits of entropy; nobody can guess inputs to try. When the user clicks the link, you hash what they bring, look up the row by hash, check the expiry, and delete the row so it works only once.

Variations and pitfalls

  • Six-digit codes have only a million possibilities. They're acceptable only with a short expiry (minutes), a small number of attempts, and rate limiting per account and per IP.
  • For API keys, add a readable prefix such as ick_live_ before the random part. It makes leaked keys easy to spot in logs and by secret scanners, and it costs nothing.
  • On .NET 9 and later, System.Buffers.Text.Base64Url.EncodeToString replaces the hand-written ToBase64Url. The manual version keeps the recipe working on .NET 8.
  • Put reset tokens in the URL path or a query string only over HTTPS, and set Referrer-Policy: no-referrer on the reset page so the token doesn't leak to third-party scripts through the Referer header.
  • For session-style tokens your own app issues and reads back, ASP.NET Core's Data Protection ITimeLimitedDataProtector can carry the user ID and expiry inside the token itself.