DEV Community

Cover image for How to Generate a Random String (Secure & Easy Methods in JavaScript, Python, PHP & Bash)
Maria Wasti
Maria Wasti

Posted on

How to Generate a Random String (Secure & Easy Methods in JavaScript, Python, PHP & Bash)

Learn how to generate a random string in JavaScript, Python, PHP, and Bash. Avoid the Math.random() trap and copy secure examples for tokens and IDs.

A random string shows up everywhere: session IDs, API keys, password reset tokens, temporary file names, and unique database identifiers. Most of us write a quick helper for it, and it works fine until someone asks whether the string is predictable.

That question matters more than it sounds. In JavaScript, Math.random() looks random, but it is a pseudo-random generator. If an attacker can observe enough of its output, they can predict the next values. Using it for a password reset token or an API key creates a real security hole.

Common Pitfalls

  • Predictable sources: Math.random(), rand(), random.random(), or timestamps.
  • Modulo bias: mapping random bytes to characters with % makes some characters appear more often than others when the charset size doesn't divide 256.
  • Collisions: short strings repeat quickly at scale.
  • Unsafe characters: characters that break URLs, JSON, or SQL.

The fix is a cryptographically secure random number generator (CSPRNG) plus a charset and length that fit the use case.

JavaScript (Browser and Node.js)

Browser-safe version with crypto.getRandomValues():

function generateRandomString(length = 16) {
  const chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
  const bytes = new Uint8Array(length);
  crypto.getRandomValues(bytes);
  let result = '';
  for (let i = 0; i < length; i++) {
    result += chars[bytes[i] % chars.length];
  }
  return result;
}

console.log(generateRandomString(20));
Enter fullscreen mode Exit fullscreen mode

Node.js, returning a hex token:

const crypto = require('crypto');

const token = crypto.randomBytes(24).toString('hex'); // 48 hex characters
console.log(token);
Enter fullscreen mode Exit fullscreen mode

The % in the browser example introduces a small modulo bias, because 256 isn't evenly divisible by 62. For most apps that's acceptable. For strict requirements, use rejection sampling or the hex/base64 output from randomBytes().

Don't do this for anything security-related:

// Insecure: predictable, do not use for tokens or passwords
Math.random().toString(36).substring(2, 12);
Enter fullscreen mode Exit fullscreen mode

Python

Use the secrets module (Python 3.6+). The random module is not suitable for tokens.

import secrets
import string

def generate_random_string(length=16):
    chars = string.ascii_letters + string.digits
    return ''.join(secrets.choice(chars) for _ in range(length))

print(generate_random_string(20))
Enter fullscreen mode Exit fullscreen mode

For a hex token or a URL-safe token:

import secrets

print(secrets.token_hex(16))      # 32 hex characters
print(secrets.token_urlsafe(24))  # URL-safe Base64 string
Enter fullscreen mode Exit fullscreen mode

PHP

rand() and mt_rand() are not cryptographically secure. Use random_int() and random_bytes() (PHP 7+).

<?php
function generateRandomString(int $length = 16): string {
    $chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
    $result = '';
    $max = strlen($chars) - 1;
    for ($i = 0; $i < $length; $i++) {
        $result .= $chars[random_int(0, $max)];
    }
    return $result;
}

echo generateRandomString(20), PHP_EOL;

// Hex token
echo bin2hex(random_bytes(16)), PHP_EOL;
Enter fullscreen mode Exit fullscreen mode

Bash (Linux and macOS)

# 20 random alphanumeric characters
LC_ALL=C tr -dc 'A-Za-z0-9' < /dev/urandom | head -c 20; echo

# Secure hex token with OpenSSL
openssl rand -hex 16
Enter fullscreen mode Exit fullscreen mode

Choosing Length and Charset

Use case Suggested length Charset
Session ID 32+ chars Hex or alphanumeric
API key 32 to 64 chars Alphanumeric
Password reset token 32+ chars URL-safe
Temporary file name 8 to 12 chars Lowercase alphanumeric
Short invite code 6 to 8 chars Uppercase, no 0 O 1 I

As a rule of thumb, security tokens should carry at least 128 bits of randomness. Sixteen random bytes gives you that.

Mistakes to Avoid

  1. Using Math.random(), rand(), or random.random() for tokens.
  2. Deriving "random" strings from timestamps or user IDs. They're guessable.
  3. Generating very short strings for unique IDs. A 4-character code will collide at scale.
  4. Skipping the uniqueness check. Enforce a unique constraint in the database.
  5. Storing long-lived secrets in plain text. Hash them before saving.

FAQ

What's the best way to generate a random string?
Use a CSPRNG: secrets in Python, crypto.randomBytes() or crypto.getRandomValues() in JavaScript, and random_bytes() or random_int() in PHP.

Is Math.random() safe for passwords or tokens?
No. It isn't cryptographically secure, and its output can be predicted.

How long should a random string be?
For security tokens, aim for at least 128 bits, about 22 alphanumeric characters or 16 random bytes in hex.

Can two random strings ever be the same?
Yes, though it's extremely unlikely with long strings. Enforce uniqueness at the database level if the value must be unique.


If you're working on a site that needs to rank, convert, and stay technically healthy, Scriptbaker does SEO audits, technical optimization, content strategy, and digital marketing. Get free audit for your site today.

Top comments (0)