Why Cryptographic Randomness Matters
Predictable tokens are a major security vulnerability. If an attacker can guess a session token, they can hijack user accounts. Math.random() uses algorithms like xorshift128+ whose internal state can be recovered from observed outputs. The Web Crypto API's getRandomValues() draws from the operating system's entropy pool, collecting randomness from hardware events, making prediction computationally impossible.
Understanding Character Sets and Entropy
Entropy measures the unpredictability of a token in bits. Each character contributes log2(charset_size) bits. Alphanumeric tokens use 62 characters giving about 5.95 bits per character. Hex tokens use 16 characters giving exactly 4 bits per character. For a target of 128 bits of security, you need 22 alphanumeric characters or 32 hex characters. Longer tokens with larger character sets provide exponentially more protection.
Token Generation Best Practices
Always use cryptographically secure random number generators for security tokens. Never truncate or modify tokens after generation as this can reduce entropy. Store tokens securely using hashing for database storage. Set appropriate expiration times for session tokens. Use different tokens for different purposes — never reuse an API key as a session token. Rotate tokens periodically to limit the impact of potential compromises.
Common Token Formats and Standards
Different applications require different token formats. UUID v4 uses 122 random bits in a specific hex format. JWT tokens encode claims with a random signature. OAuth2 uses opaque bearer tokens that should be at least 128 bits of entropy. Database API keys often use Base64 or alphanumeric encoding for URL safety. Choose the format that best fits your application's requirements and transport constraints.





