What is a cryptographic random token?

A cryptographic random token is a fixed-length string generated from a cryptographically secure source of randomness. Unlike tokens produced by standard pseudo-random number generators (like Math.random()), cryptographically secure tokens are computationally unpredictable — even if an attacker knows all previous tokens generated by the system, they cannot predict the next one.

This tool generates tokens using the Web Crypto API (crypto.getRandomValues()), which draws from the same entropy pool as your operating system's CSPRNG — the same source used to generate TLS session keys and SSH keys. The randomness quality is identical to what you would get from openssl rand or /dev/urandom.

Everything runs in your browser — no token is ever sent to a server. All generation happens locally, making this tool safe for generating production secrets.

Token formats explained

Hexchars: 0–9, a–fefficiency: 50% — 1 byte = 2 chars
a3f2b1e4c9d87654321a3f2b1e4c9d876

Universal. Works in any context — URLs, headers, JSON, logs. The most readable format. Preferred for hashes, session IDs, and any context where the token needs to be inspected.

Base64chars: A–Z, a–z, 0–9, +, /efficiency: 75% — 3 bytes = 4 chars
o/K1xJy8dlU=

More compact than hex. The + and / characters require URL-encoding in query strings, so Base64 is best for HTTP headers, email content, and binary data transmission (like email attachments or data URIs).

Base64urlchars: A–Z, a–z, 0–9, -, _efficiency: 75% — same as Base64, no padding
o_K1xJy8dlU

URL-safe Base64. No padding characters. Used in JWTs, OAuth tokens, and anywhere the token will appear in a URL path or query string. The format used by crypto.randomUUID() for UUID v4.

Alphanumericchars: A–Z, a–z, 0–9efficiency: ~60% — slightly less than Base64
Xk9mL2vQ8nDp4rTy

Universally safe — no special characters to escape in any context. Slightly lower entropy per character than hex or Base64. Best for tokens that will appear in user-facing contexts, SMS messages, or systems with restricted character sets.

How many bytes do I need?

The required length depends on the security requirements of the token's use case. More bytes = more entropy = harder to guess or brute-force:

BytesEntropyUse caseLength in hex
16128 bitsCSRF tokens, short-lived codes32 hex chars
24192 bitsSession tokens, email verify links48 hex chars
32256 bitsAPI secrets, JWT signing keys64 hex chars
48384 bitsLong-lived API keys, root secrets96 hex chars
64512 bitsMaster secrets, key derivation128 hex chars

Generating tokens in code

Always use your language's cryptographic random module. Never use general-purpose random functions for security-sensitive tokens:

JavaScript / Node.js
crypto.randomBytes(32).toString('hex')  // Node.js
crypto.getRandomValues(new Uint8Array(32))  // Browser
Python
import secrets
secrets.token_hex(32)        # hex
secrets.token_urlsafe(32)    # base64url
Go
import "crypto/rand"
import "encoding/hex"
bytes := make([]byte, 32)
rand.Read(bytes)
hex.EncodeToString(bytes)
PHP
bin2hex(random_bytes(32))  // hex
base64_encode(random_bytes(32))  // base64
Ruby
require "securerandom"
SecureRandom.hex(32)
SecureRandom.base64(32)
SecureRandom.urlsafe_base64(32)

Token security and best practices

Never use Math.random() for security

Math.random() is a pseudo-random number generator seeded with a predictable value. It is not suitable for security tokens — an attacker who observes several outputs can reconstruct the internal state and predict future values. Always use crypto.getRandomValues() or your language's equivalent.

Store secrets in environment variables

Never hardcode tokens or secrets in source code. Use .env files locally, CI/CD secret variables for pipelines, and dedicated secrets managers (AWS Secrets Manager, Vault, Doppler) in production. Add .env to .gitignore before your first commit and keep it there.

Rotate tokens on security events

Immediately invalidate and regenerate tokens when: a team member with access leaves, you suspect a token was exposed in logs or error messages, or a dependency vulnerability is disclosed. For API keys, maintain a grace period where both old and new tokens work to avoid service disruption.

Use token hashing for database storage

Store SHA-256(token) in the database, never the plaintext token. Show the full token to the user exactly once at creation. On subsequent requests, hash the received token and compare. This prevents database breaches from yielding usable credentials. See Hash Generator for SHA-256 hashing.

Set appropriate token expiry

Short-lived tokens for interactive sessions (15–60 minutes), medium-lived for API access (24 hours for developer APIs), long-lived for server-to-server keys that are rotated manually. Combine with refresh token patterns for interactive apps.

For generating structured API keys with custom prefixes, use the API Key Generator. For HMAC signing of tokens and webhooks, use the HMAC Generator.

FAQ

Common questions

Is this token generator cryptographically secure?

Yes. All tokens are generated using the Web Crypto API (crypto.getRandomValues()), which uses the operating system's cryptographically secure pseudo-random number generator (CSPRNG). This is the same entropy source used by your operating system for TLS keys, SSH keys, and other security-critical operations.

How many bytes should I use for an API secret or session token?

32 bytes (256 bits) is the recommended minimum for API secrets, signing keys, and session tokens. This gives 256 bits of entropy — far beyond practical brute-force. 16 bytes (128 bits) is acceptable for shorter-lived tokens like CSRF tokens. Never use less than 16 bytes for security-sensitive tokens.

What is the difference between hex, Base64, and alphanumeric formats?

Hex encodes each byte as two characters (0–9, a–f), producing a string twice the byte count. Base64 encodes 3 bytes as 4 characters using A–Z, a–z, 0–9, +, /. Base64url replaces + with - and / with _ for safe use in URLs and JWTs. Alphanumeric uses only letters and digits — slightly less efficient but universally safe in any context.

Which format should I use for JWT secret keys?

For HS256/HS384/HS512 JWT signing, use a hex or Base64url secret with at least 256 bits of entropy (32 hex bytes = 64 hex characters, or 32 bytes as Base64url). Many JWT libraries accept the raw string directly. For RS256 or ES256, generate a proper RSA or EC key pair instead.

Can I use these tokens as database IDs?

Yes, but consider the trade-offs. Random tokens as IDs are not sortable by creation time (unlike UUID v7 or ULID). For primary keys in high-write databases, this can cause B-tree index fragmentation. For secondary identifiers (public-facing IDs, shareable links, invite codes), random tokens are excellent because they prevent enumeration attacks.

How do I store generated secrets securely in my application?

Store secrets in environment variables, not in source code or config files. Use a secrets manager (AWS Secrets Manager, HashiCorp Vault, Doppler) in production. Never commit secrets to version control — use .gitignore for .env files and tools like git-secrets or gitleaks to scan for accidental commits. Rotate secrets immediately if they are ever exposed.

What is the difference between a token and a password?

A password is chosen by a human (memorable, limited entropy). A token is machine-generated (maximum entropy for its length, no dictionary words). Tokens are used for machine-to-machine authentication where memorability is not required. Tokens should be treated as secrets: never log them, rotate them regularly, and revoke them immediately if compromised.

How do I generate tokens like this in code?

In JavaScript/Node.js: crypto.randomBytes(32).toString("hex"). In Python: secrets.token_hex(32). In Go: crypto/rand.Read(). In PHP: bin2hex(random_bytes(32)). Always use the language's cryptographic random module (secrets, crypto/rand) — never Math.random() or random.random() for security tokens.

More in Security