Random String Generator: Secure Tokens
Generate cryptographically secure random strings — hex, alphanumeric, custom character sets.
Published:
Tags: random string generator, secure token generator, random password string
Random String Generator: Secure Tokens Part of our complete guide to this topic — see the full series. A random string generator that uses your OS entropy pool produces tokens that no attacker can predict, even knowing the algorithm. One that relies on can be broken in milliseconds given a few samples. This guide explains the mechanics, the math, and the correct implementation. --- The Core Problem: Predictability Session tokens, API keys, password-reset links, and CSRF tokens must be unpredictable to anyone who does not hold them. If an attacker can guess a valid token, they can impersonate users, reset passwords without authorization, or bypass request forgery protections. Predictability comes from two sources: Weak entropy source — seeded PRNGs like produce sequences that can be…
Frequently Asked Questions
How do I generate a random string?
Draw random bytes from crypto.getRandomValues() and map them to your chosen alphabet. For hex, encode each byte as two hex digits. For alphanumeric, sample bytes and use modulo reduction or rejection sampling against your character set. Never use Math.random() for strings that will serve as secrets.
How do I generate a secure random token?
Call crypto.getRandomValues(new Uint8Array(32)) to get 32 bytes (256 bits of entropy), then hex-encode or base64url-encode the result. 32 bytes is the standard minimum for CSRF tokens, API keys, and password-reset links per OWASP ASVS v4.0 §3.3.1.
What character sets can I use for random strings?
Common choices are hex (0-9a-f, 4 bits/char), base64url (A-Za-z0-9-_, 6 bits/char), alphanumeric (A-Za-z0-9, 5.95 bits/char), and printable ASCII (95 chars, 6.57 bits/char). Shorter character sets require longer strings to achieve the same entropy.
How do I generate a random hex string?
Sample N bytes with crypto.getRandomValues(new Uint8Array(N)) and convert: Array.from(bytes).map(b => b.toString(16).padStart(2, '0')).join(''). Each byte produces two hex characters, so 16 bytes → 32-char hex string with 128 bits of entropy.
Is Math.random() secure for tokens?
No. Math.random() uses an internal PRNG algorithm (xorshift128+ in V8) whose 128-bit state can be fully recovered from 3 consecutive outputs. An attacker who observes a few tokens can predict all future ones. Always use crypto.getRandomValues() or a cryptographic library for security-sensitive strings.
All articles · theproductguy.in