Random String Generator

Generate random strings for tokens, API keys, invite codes and other developer-focused identifiers.

Back to all tools on ToolForge

More in Generators

Need a password instead? Use the Password Generator.

String Options

Length:

Result

About Random String Generator

This random string generator creates custom strings for API keys, invite codes, test data, short identifiers and other development tasks. It uses cryptographically secure random number generation (CSPRNG) via the Web Crypto API when available, falling back to Math.random for older browsers. You can choose a preset such as Base62, hex or URL-safe output, or switch to a custom character mix.

It is useful for generating API keys, authentication tokens, session IDs, CSRF tokens, invite codes, database IDs, test data fixtures, short URLs, and unique identifiers for development and testing.

Random Number Generation

The quality of randomness is critical for security-sensitive applications:

Random Sources:

1. Math.random (Standard)
   - Pseudo-random number generator (PRNG)
   - Uses algorithmic seed (often current time)
   - Suitable for: games, sampling, non-security uses
   - NOT suitable for: tokens, keys, passwords
   - Period: Implementation-dependent

2. crypto.getRandomValues (Secure)
   - Cryptographically secure PRNG (CSPRNG)
   - Uses OS entropy sources
   - Suitable for: tokens, API keys, session IDs
   - Backed by: /dev/urandom (Unix), CryptGenRandom (Windows)
   - Standard: Web Crypto API (W3C Recommendation)

Implementation:
  // Secure random (preferred)
  const array = new Uint32Array(1);
  crypto.getRandomValues(array);
  const random = array[0] / (0xFFFFFFFF + 1);

  // Fallback (less secure)
  const random = Math.random();

Detection:
  if (window.crypto && crypto.getRandomValues) {
    // Use secure random
  } else {
    // Fallback to Math.random
  }

Character Set Reference

Preset Characters Size Bits/Char Use Case
Hex 0-9, a-f 16 4.0 Binary data, hashes
Base62 a-z, A-Z, 0-9 62 5.95 General tokens
URL-safe a-z, A-Z, 0-9, -, _ 64 6.0 URLs, JWT
Alphanumeric a-z, 0-9 36 5.17 Simple codes
Full ASCII Printable ASCII (33-126) 94 6.55 Maximum entropy
Numeric Only 0-9 10 3.32 PIN codes, OTP

Entropy and Security

Entropy Calculation:
  Entropy (bits) = length × log2(characterSetSize)

  Examples:
  - 16-char Base62: 16 × 5.95 = 95.2 bits
  - 32-char hex:    32 × 4.0  = 128 bits
  - 24-char URL:    24 × 6.0  = 144 bits
  - 8-char numeric: 8 × 3.32  = 26.6 bits

Security Recommendations:

Purpose                    | Min Entropy | Example Length (Base62)
---------------------------|-------------|------------------------
Session ID                 | 64 bits     | 11 characters
CSRF Token                 | 64 bits     | 11 characters
API Key                    | 128 bits    | 22 characters
Password Reset Token       | 128 bits    | 22 characters
Invite Code (short-lived)  | 40 bits     | 7 characters
Database ID (unique)       | 64 bits     | 11 characters

Brute Force Resistance:
  64 bits:  18.4 quintillion combinations
  128 bits: 3.4 × 10^38 combinations
  256 bits: 1.1 × 10^77 combinations

Time to crack (assuming 1 billion guesses/second):
  64 bits:  ~584 years
  128 bits: ~10^22 years (longer than universe age)

Common Use Cases

Use Case Recommended Length Character Set Notes
API Keys 32+ characters Base62 or URL-safe High entropy, store hashed
Session IDs 32+ characters Hex or Base62 Regenerate on privilege change
CSRF Tokens 16-32 characters Base62 Per-session or per-request
Invite Codes 8-16 characters Uppercase + digits Exclude ambiguous chars (0/O, 1/I)
Short URLs 6-10 characters Base62 Encode sequential ID
Test Data Variable Any Reproducible seed optional
Database IDs 12-16 characters Base62 or Crockford ULID, NanoID format

Code Examples by Language

JavaScript (Browser):
  // Using Web Crypto API
  function generateRandom(length, charset) {
    const array = new Uint32Array(length);
    crypto.getRandomValues(array);
    let result = '';
    for (let i = 0; i < length; i++) {
      result += charset[array[i] % charset.length];
    }
    return result;
  }

  // Base62 example
  const base62 = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
  generateRandom(16, base62);

JavaScript (Node.js):
  // Using crypto module
  const crypto = require('crypto');

  function generateRandom(length, charset) {
    const buffer = crypto.randomBytes(length);
    let result = '';
    for (let i = 0; i < length; i++) {
      result += charset[buffer[i] % charset.length];
    }
    return result;
  }

Python:
  import secrets
  import string

  # Secure random string
  def generate(length=16, charset=None):
      if charset is None:
          charset = string.ascii_letters + string.digits
      return ''.join(secrets.choice(charset) for _ in range(length))

  # Hex token
  secrets.token_hex(16)  # 32-char hex

  # URL-safe token
  secrets.token_urlsafe(16)  # ~24 chars

PHP:
  // PHP 7+ using random_bytes
  function generateRandom($length = 16, $charset = null) {
      if ($charset === null) {
          $charset = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
      }
      $result = '';
      $charsetLen = strlen($charset);
      for ($i = 0; $i < $length; $i++) {
          $result .= $charset[random_int(0, $charsetLen - 1)];
      }
      return $result;
  }

  // Hex token
  bin2hex(random_bytes(16));  // 32-char hex

Java:
  // Using SecureRandom
  import java.security.SecureRandom;

  public String generateRandom(int length, String charset) {
      SecureRandom random = new SecureRandom();
      StringBuilder result = new StringBuilder(length);
      for (int i = 0; i < length; i++) {
          result.append(charset.charAt(random.nextInt(charset.length())));
      }
      return result.toString();
  }

C#:
  // Using RandomNumberGenerator
  using System.Security.Cryptography;

  public string GenerateRandom(int length, string charset) {
      var rng = RandomNumberGenerator.Create();
      var data = new byte[length];
      rng.GetBytes(data);
      var result = new StringBuilder(length);
      for (int i = 0; i < length; i++) {
          result.Append(charset[data[i] % charset.Length]);
      }
      return result.ToString();
  }

Random String Examples

Example 1: Base62 Token (16 chars)
  Output: "kL9mN2pQ4rS6tU8v"
  Use: API key component, session ID

Example 2: Hex Token (32 chars)
  Output: "a3f7c2e1b9d8f4a6c0e5b7d2f8a1c3e9"
  Use: Binary hash representation, MD5/SHA format

Example 3: URL-safe String (24 chars)
  Output: "Ab3cD4eF5gH6iJ7kL8mN9oP0"
  Use: JWT payload, URL parameter

Example 4: Invite Code (8 chars, uppercase + digits)
  Output: "X7K9M2P4"
  Use: User invitation, referral code

Example 5: Numeric PIN (6 digits)
  Output: "482716"
  Use: OTP, verification code

Example 6: Short URL ID (7 chars)
  Output: "aB3dE7g"
  Use: URL shortener (bit.ly style)

Example 7: UUID-like (36 chars with hyphens)
  Output: "f47ac10b-58cc-4372-a567-0e02b2c3d479"
  Use: Database primary key, unique identifier

Example 8: NanoID-style (21 chars)
  Output: "V1StGXR8_Z5jdHi6B-myT"
  Use: Document ID, resource identifier

Special Character Sets

Crockford's Base32:
  Characters: 0123456789ABCDEFGHJKMNPQRSTVWXYZ
  Excludes: I, L, O, U (avoid confusion and profanity)
  Use case: Human-readable codes, verbal transmission

  Example: "CSQPYR8M3"

Base64 (standard):
  Characters: A-Za-z0-9+/
  Padding: = (for length alignment)
  Use case: Binary data encoding

  Example: "SGVsbG8gV29ybGQ="

Base64URL (URL-safe Base64):
  Characters: A-Za-z0-9-_
  Replaces: + → -, / → _
  Use case: JWT, URL parameters

  Example: "SGVsbG8gV29ybGQ"

Decimal Only:
  Characters: 0123456789
  Use case: PIN codes, phone-style codes

  Example: "847261"

Uppercase + Digits (alphanumeric):
  Characters: ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789
  Use case: Product keys, license codes

  Example: "XKCD42A7B9"

Ambiguous Character Exclusion:
  Exclude: 0, O, 1, I, l (look similar)
  Use case: Manual entry, printed codes

  Safe set: "23456789ABCDEFGHJKMNPQRSTUVWXYZ"

Best Practices

Limitations

Frequently Asked Questions

What is the difference between random and secure random?
Standard random (Math.random) uses pseudo-random algorithms suitable for games and sampling. Secure random (crypto.getRandomValues) uses cryptographically secure random number generation (CSPRNG) suitable for tokens, API keys, and security-sensitive identifiers. This tool uses crypto.getRandomValues when available.
What are Base62 and hex character sets?
Base62 uses a-z, A-Z, and 0-9 (62 characters) for compact, readable identifiers. Hex uses only 0-9 and a-f (16 characters) for binary data representation. Base62 produces shorter strings; hex is useful for hashes and binary-compatible output.
How long should random tokens be?
For API keys and tokens: 32+ characters. For invite codes: 8-16 characters. For session IDs: 32+ characters. For CSRF tokens: 16-32 characters. Longer strings have exponentially more entropy and are harder to guess through brute force.
What is URL-safe encoding?
URL-safe strings use only alphanumeric characters plus hyphen (-) and underscore (_). They avoid special characters that require URL encoding (+, /, =, etc.). Base64URL is a common URL-safe variant used in JWT tokens and web applications.
How is entropy calculated for random strings?
Entropy (in bits) = length × log2(characterSetSize). For Base62: each character adds ~5.95 bits. For hex: each character adds 4 bits. A 16-character Base62 string has ~95 bits of entropy; a 32-character hex string has 128 bits.
When should I use this tool vs a password generator?
Use this tool for API keys, tokens, invite codes, and developer identifiers. Use a password generator for user-facing passwords with memorability considerations, password policy requirements, and strength validation.