Random String Generator

Generate cryptographically secure random strings — tokens, API keys, passwords, slugs, and more. Processing done server-side with PHP's random_int().

Frequently Asked Questions

PHP's random_int() and random_bytes() use the operating system's CSPRNG (cryptographically secure pseudo-random number generator). While modern browsers also expose crypto.getRandomValues(), server-side generation ensures the randomness is never exposed to client-side JavaScript that could be intercepted by browser extensions or scripts on the page.

Hex strings (0–9 a–f) are URL-safe and often used for session tokens, CSRF tokens, and API keys. A 32-character hex string contains 128 bits of entropy (since each hex digit encodes 4 bits), which is widely considered sufficient for security tokens.

A CSPRNG (Cryptographically Secure Pseudo-Random Number Generator) draws entropy from the operating system's entropy pool (hardware noise, interrupt timing, CPU jitter) and produces output that is computationally indistinguishable from true random data. Knowing past or future outputs is infeasible without the internal state. A regular PRNG (like Math.random() or rand()) uses a simple algorithm seeded with a predictable value — fast and sufficient for simulations, but never safe for security tokens. PHP's random_bytes() and random_int() both use the OS CSPRNG.

Entropy measures the unpredictability of a value in bits. For a random string, entropy = log₂(charset_size) × length. A 32-character string from a 62-character alphanumeric charset has log₂(62) × 32 ≈ 190 bits of entropy — far beyond brute-force reach. A 16-character hex string gives 4 × 16 = 64 bits — still reasonably secure for low-risk tokens. Each additional character in the string multiplies the possible values by the charset size, making length the most powerful factor in token security.

Common security applications: API keys — 32+ character alphanumeric strings used to authenticate API clients; session tokens — 32+ character random hex or base-64 strings stored in cookies; password reset links — short-lived 48+ character tokens emailed to users; 2FA backup codes — groups of 8–10 character codes; CSRF tokens — 32+ character tokens embedded in forms; invite/referral codes — 8–12 character alphanumeric strings; temporary file names — random names to prevent path guessing; idempotency keys — unique request IDs for payment and API calls.

When humans need to read, type, or speak a code aloud — activation keys, invite codes, 2FA backup codes, printed tokens — ambiguous characters cause errors. The characters 0 (zero) and O (capital oh), 1 (one) and l (lowercase L) and I (capital eye) look nearly identical in many fonts. Removing them reduces the effective charset from 62 to 55 for alphanumeric strings — a slight entropy decrease that is far outweighed by the usability improvement. For machine-to-machine tokens (API keys, session IDs), keep the full charset since humans never type them.

OWASP recommends a minimum of 128 bits of entropy for security tokens. In practice: hex strings need 32 characters (128 bits), alphanumeric strings need 22 characters (≈131 bits), and base-64 strings need 22 characters (≈132 bits). For API keys visible to developers, 32+ characters is standard. For password reset tokens, use 48+ characters (one-time use, but highly sensitive). For session tokens, PHP's default session ID is 128-bit — don't go lower. Shorter tokens are acceptable only for short-lived, rate-limited contexts like OTP codes.

Several commands generate cryptographically secure random strings: OpenSSL: openssl rand -base64 32 (44 base-64 chars ≈ 256 bits) or openssl rand -hex 32 (64 hex chars); urandom (Linux/macOS): head -c 32 /dev/urandom | base64; Python: python3 -c "import secrets; print(secrets.token_urlsafe(32))"; Node.js: node -e "console.log(require('crypto').randomBytes(32).toString('hex'))"; PHP CLI: php -r "echo bin2hex(random_bytes(32));". All of these use the OS CSPRNG and are safe for production use.

A seeded PRNG produces a deterministic sequence from a starting seed value — given the same seed, it always produces the same output. This is useful for reproducible simulations, game maps, and testing, but catastrophic for security. If an attacker can guess or observe the seed (e.g., the current timestamp, process ID, or a sequential counter), they can predict all past and future "random" values. Many real-world attacks have exploited weak seeds. Example: early PHP rand() seeded with microtime() was predictable by timing HTTP responses. Always use random_bytes()/random_int() (PHP), crypto.getRandomValues() (JS), or secrets (Python) for any security-sensitive randomness.

URL-safe strings use only characters that do not require percent-encoding in URLs: alphanumeric characters plus - and _ (or just alphanumeric). When API keys are passed as query parameters (?api_key=...), characters like +, /, and = (common in base-64) become percent-encoded (%2B, %2F, %3D), creating mismatches if the receiver decodes inconsistently. URL-safe base-64 (RFC 4648) substitutes - for + and _ for /, with no padding =. JWT tokens, PKCE code verifiers, and OAuth tokens all use URL-safe encoding for this reason.

About This Random String Generator

This free random string generator creates cryptographically random strings of configurable length using any combination of uppercase letters, lowercase letters, digits, and custom characters. All generation happens in your browser using the Web Crypto API — nothing is sent to a server.

When to use this tool

  • Generating API keys, secret tokens, and session identifiers
  • Creating random one-time codes and nonces
  • Producing test data with random string values
  • Generating unique file names or object keys

How Random String Generation Works

Every string is generated server-side using PHP's CSPRNG — cryptographically secure pseudo-random number generator — for maximum unpredictability.

Build Character Pool

The selected charset (alphanumeric, hex, symbols, or custom) is assembled into a pool string. The pool's length determines the entropy per character: a 62-char alphanumeric pool gives log₂(62) ≈ 5.95 bits per character.

Cryptographic Index Selection

For each position, PHP's random_int(0, strlen($pool)-1) picks a uniformly random index using the operating system's entropy source (e.g., /dev/urandom on Linux). No modular bias is introduced.

Return as JSON Array

The requested number of strings (up to 50) are generated in a single PHP request and returned together. Each string is independently random — no two are derived from each other.

Common Use Cases

API Keys & Access Tokens

Generate 32–64 character hex or alphanumeric strings for API keys. Store only the hash (see Hash Generator), never the plaintext key, to limit exposure on database breach.

CSRF & Session Tokens

Session IDs and CSRF tokens must be unpredictable. A 32-char hex token (128 bits of entropy) meets OWASP's minimum recommendations. Generate fresh tokens here to use in security testing or prototype apps.

Email Verification Codes

A 6–8 character numeric or alphanumeric token is easy for users to copy from email. Generate verification codes for email confirmation, SMS OTP, and 2FA flows with the numeric or short-alphanumeric preset.

Short URL Slugs

6–8 character alphanumeric strings make collision-resistant, URL-safe slugs for short links, invite codes, and shareable resource IDs. The 62-character pool gives 56 billion unique combinations at length 6.

Encryption Secrets & Salts

Application secret keys (for AES, JWT signing, cookie encryption) should be 32+ character hex strings (256-bit). Generate one here when bootstrapping a new application environment.

Database Seed Data

When seeding a test database with randomized records, generate batches of up to 50 strings at once for usernames, order numbers, SKUs, and other string fields that need to be unique and realistic-looking.

Related Articles

View all articles
UUID v4 vs UUID v7 vs ULID vs NanoID: Which Identifier Format Should You Use?

UUID v4 vs UUID v7 vs ULID vs NanoID: Which Identifier Format Should You Use?

UUID v4's random bits fragment database B-tree indexes, causing write amplification. UUID v7 adds a millisecond timestamp prefix to fix this. ULID is sortable and URL-safe without hyphens. NanoID is compact and customisable. Here's how each works and when to choose each format.

Jun 13, 2026
Secure Randomness: Why Math.random() Fails for Security Tokens — and the Right Alternatives

Secure Randomness: Why Math.random() Fails for Security Tokens — and the Right Alternatives

Math.random() in JavaScript is predictable from 128 observations. Python's random module explicitly warns it's not for security. Here's why PRNGs fail for tokens, the secure alternatives in every major language, and the specific bit lengths needed for different security contexts.

Jun 9, 2026
How Long Does a Random String Need to Be? The Birthday Problem Explained

How Long Does a Random String Need to Be? The Birthday Problem Explained

How long does a random string need to be? The birthday problem shows that 6-character codes collide far sooner than most developers expect. Here's how to calculate the right length for tokens, IDs, and API keys.

Jun 8, 2026
Random String Generator — Secure Tokens, API Keys & Test Data

Random String Generator — Secure Tokens, API Keys & Test Data

Learn when and how to generate random strings for session tokens, API keys, OTPs, and test data — what character sets to use, how long they should be, and what entropy actually means in practice.

Jun 6, 2026