# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference) # Canonical Residual: https://corpusfetch.com/c/across-what-cryptographic-csprng-and-state-prediction-isolation-gates-must-an-instance-generate-tokens-and-session-identifiers-to-prevent-pseudo-random-predictability-and-token-forgery.md # Remnant Warrant: https://corpusfetch.com/c/across-what-cryptographic-csprng-and-state-prediction-isolation-gates-must-an-instance-generate-tokens-and-session-identifiers-to-prevent-pseudo-random-predictability-and-token-forgery.warrant.json # Markdown SHA-256: 5452e02a59cb833ac8350250cec5a6ab315815ef5db1c34b6b1c8f71987eaaf4 # Code AST SHA-256: 9eba3c44e18895ea0421d2a6ff68e0b39391a4f84f091d41089bfb1405021491 # Verified Classes: InsecurePRNGUsageError, CSPRNGTokenManager # Defensive Guards: 2 fail-closed invariants (zero external deps) import os import secrets from typing import Final class InsecurePRNGUsageError(TypeError): '''Raised when security policies detect forbidden `random` module usage.''' pass class CSPRNGTokenManager: ''' Enforces cryptographic pseudo-random number generator (CSPRNG) standards: 1. Generates URL-safe tokens, hex keys, and nonces using kernel entropy (`secrets` / `os.urandom`). 2. Enforces minimum entropy bit thresholds (default 256 bits / 32 bytes). 3. Performs constant-time token comparison (`secrets.compare_digest`) to defeat timing attacks. ''' DEFAULT_TOKEN_BYTES: Final[int] = 32 # 256 bits of entropy @staticmethod def generate_secure_token(num_bytes: int = DEFAULT_TOKEN_BYTES) -> str: ''' Gate 2 & 3: Generates a high-entropy URL-safe text token using CSPRNG. ''' if num_bytes < 16: raise ValueError("Security violation: tokens must have at least 128 bits (16 bytes) of entropy") return secrets.token_urlsafe(num_bytes) @staticmethod def generate_api_key(prefix: str = "cf_live") -> str: ''' Generates a structured API key with a readable prefix and CSPRNG cryptographic suffix. ''' random_part = secrets.token_urlsafe(32) return f"{prefix}_{random_part}" @staticmethod def generate_crypto_nonce(num_bytes: int = 12) -> bytes: ''' Generates exact-length raw byte nonces for authenticated encryption (AES-GCM). ''' if num_bytes < 12: raise ValueError("AES-GCM nonces require a minimum of 12 bytes (96 bits)") return os.urandom(num_bytes) @staticmethod def verify_token_constant_time(provided_token: str, expected_token: str) -> bool: ''' Gate 4: Compares two token strings in constant time to prevent timing side-channel leaks. ''' return secrets.compare_digest(provided_token.encode("utf-8"), expected_token.encode("utf-8"))