Random String Generator: Create Secure Random Strings

From passwords to API keys — learn how to generate random strings that are truly unpredictable and secure.

Security Tools 2026-04-09 By Risetop Team 10 min read

Every developer needs random strings — for API keys, session tokens, test data, temporary passwords, and dozens of other purposes. But there's a critical difference between a string that looks random and one that is actually random. If you're generating security-sensitive strings with Math.random(), you're doing it wrong.

This guide covers what makes a random string secure, how to calculate its strength, and how to generate one properly in any programming language.

What Makes a Random String "Secure"?

A secure random string must satisfy two requirements:

  1. Cryptographic randomness: The generator must use a CSPRNG (Cryptographically Secure Pseudo-Random Number Generator) that draws entropy from the operating system — not a deterministic algorithm like a linear congruential generator.
  2. Sufficient entropy: The string must be long enough and use a large enough character set to resist brute-force attacks.

CSPRNG vs PRNG: Why It Matters

A regular PRNG (like Math.random() in JavaScript or random.random() in Python) is pseudorandom — it uses a mathematical formula to produce numbers that appear random but are completely deterministic. If an attacker knows the algorithm and the seed value (the initial state), they can reproduce every "random" number the generator will ever produce.

A CSPRNG, on the other hand, is seeded with real entropy from the operating system — timing of keystrokes, mouse movements, disk I/O, hardware noise, and other unpredictable sources. Even if the algorithm is known, the output cannot be predicted.

⚠️ Never use these for security:
Math.random() (JavaScript) · random.random() (Python) · rand() (C) · Math.random() (Java) · Any LCG-based generator

These are fine for games, simulations, and shuffling — but never for passwords, tokens, or keys.

Understanding Entropy

Entropy is the measure of unpredictability, expressed in bits. The formula is straightforward:

Entropy (bits) = length × log₂(character_set_size)

Here's what different character sets give you:

Character Set Characters Bits per Character
Digits (0-9) 10 3.3 bits
Hexadecimal (0-9, a-f) 16 4.0 bits
Lowercase letters (a-z) 26 4.7 bits
Alphanumeric (a-z, A-Z, 0-9) 62 5.95 bits
Full ASCII printable 94 6.55 bits

So a 16-character string using the full ASCII set has: 16 × 6.55 = 104.8 bits of entropy. For comparison, AES-128 uses 128 bits. That 16-character random string is nearly as strong as a 128-bit encryption key.

How Much Entropy Do You Need?

Choosing the Right Character Set

More characters means more entropy per position — but also more complexity for humans. The right choice depends on your use case:

💡 URL-safe tip: For tokens that appear in URLs, avoid characters like +, /, =, and ?. Use Base64url encoding which substitutes + with -, / with _, and removes padding.

How to Generate Secure Random Strings

Online Random String Generator

The fastest method: use our Random String Generator Tool. Choose your character set, length, and quantity — get cryptographically random strings instantly.

JavaScript (Browser)

function generateRandomString(length, charset = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789') { const array = new Uint32Array(length); crypto.getRandomValues(array); return Array.from(array, n => charset[n % charset.length]).join(''); } // Generate a 32-character secure token console.log(generateRandomString(32)); // Base64url token (URL-safe) function generateToken(length = 32) { const array = new Uint8Array(length); crypto.getRandomValues(array); return btoa(String.fromCharCode(...array)) .replace(/\+/g, '-') .replace(/\//g, '_') .replace(/=+$/, ''); } console.log(generateToken(32));

Node.js

const crypto = require('crypto'); // Hex string (32 bytes = 64 hex characters) const hexToken = crypto.randomBytes(32).toString('hex'); console.log(hexToken); // Base64url string const base64Token = crypto.randomBytes(32) .toString('base64') .replace(/\+/g, '-') .replace(/\//g, '_') .replace(/=+$/, ''); console.log(base64Token); // Custom character set function randomString(length, charset = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789!@#$%') { const bytes = crypto.randomBytes(length); return Array.from(bytes, b => charset[b % charset.length]).join(''); } console.log(randomString(24));

Python

import secrets import string # Secure hex token token = secrets.token_hex(32) # 64 hex characters print(token) # Secure URL-safe token url_token = secrets.token_urlsafe(32) # ~43 characters print(url_token) # Custom character set def random_string(length, charset=string.ascii_letters + string.digits): return ''.join(secrets.choice(charset) for _ in range(length)) print(random_string(24)) # Generate a password alphabet = string.ascii_letters + string.digits + string.punctuation password = ''.join(secrets.choice(alphabet) for _ in range(20)) print(password)

Command Line

# OpenSSL (hex) openssl rand -hex 32 # OpenSSL (base64) openssl rand -base64 32 # /dev/urandom (Linux/macOS) head -c 32 /dev/urandom | base64 | tr -d '\n' # Python one-liner python3 -c "import secrets; print(secrets.token_urlsafe(32))"

Real-World Use Cases

1. API Keys

API keys should be long (32+ characters), URL-safe, and generated with a CSPRNG. Prefix them to identify the service (e.g., sk_live_abc123...) and store only the hash (never plaintext) in your database.

2. Session Tokens

Web session tokens need at least 128 bits of entropy. Most frameworks handle this automatically (Express uses 256-bit tokens, Django uses 128-bit), but if you're building custom authentication, don't cut corners.

3. Password Generation

The best passwords are long random strings — but humans struggle with them. Consider using diceware (random word combinations) for user-facing passwords and pure random strings for machine-to-machine credentials.

4. Test Data

For testing, you don't need cryptographic randomness — but a random string generator saves time. Generate fake emails, usernames, order IDs, or any placeholder data that looks realistic.

Common Mistakes

Random String vs UUID vs Password

These three are often confused but serve different purposes:

Generate secure random strings in seconds with our free Random String Generator Tool — customizable length, character sets, and bulk generation.

Conclusion

Generating random strings seems simple, but doing it securely requires understanding the difference between pseudorandom and cryptographically secure randomness, and ensuring sufficient entropy for your use case.

The rules are simple: use a CSPRNG (never Math.random()), choose an appropriate character set, and make the string long enough. When in doubt, 32 bytes of crypto.randomBytes() or secrets.token_urlsafe() will serve you well for virtually any purpose.