Random string generator

A free online random string generator. Cryptographically secure, uniformly distributed, and nothing is ever sent to a server.

G
More options
up to 10,000

Constraints

About this random string generator

A random string generator produces a sequence of characters where every position is picked by chance from an alphabet you choose. Developers use random strings as API keys, session tokens, password reset links, database identifiers, file names, invite codes and test data. The only thing that separates a good one from a bad one is where the randomness comes from and how it is turned into characters, and both are invisible in the output. A string that looks random is not the same as one that is.

This random string generator runs online in your browser tab and never on a server. It uses the same cryptographic source your operating system gives to password managers and TLS libraries, maps it onto characters without bias, and tells you exactly how much entropy the result carries. It is free, it needs no account, and it keeps working if you disconnect from the network after the page has loaded.

How to use it

  1. Set the length with the number box or the slider. The default is 24 characters, the slider covers 1 to 128, and the number box accepts up to 4,096.
  2. Pick a character set. The toggles switch uppercase, lowercase, digits and symbols on or off, and the dropdown offers ready-made alphabets such as hexadecimal, Base58, Base32 and Base64 URL-safe.
  3. Press Generate, or the G key. A new string appears at the top, with its strength in bits underneath.
  4. Press Copy. For more than one value, open More options, set a quantity of up to 10,000 and choose one per line, comma separated, a JSON array, a quoted list or .env assignments, then copy or download the whole batch.

Random string generator with special characters

Turning on the symbols toggle adds twelve special characters: ! # $ % * + - = ? @ ^ _. That set is chosen on purpose. Every one of them is accepted by the Microsoft Entra ID, Active Directory and OWASP password allow-lists, and none of them breaks a shell command, a URL or a quoted config value the way a backslash, a quote or a space does. Combined with letters and digits it gives an alphabet of 74 characters, or 6.2095 bits per character, only 5.3% below the full set of 94 printable ASCII characters. If you need every symbol, or a different selection, type your own alphabet into the custom character set field. The random string with special characters page goes into which systems reject which symbols.

Long random string generator

A long random string generator is useful for encryption keys, signing secrets, and filling a field to its limit to see what breaks. This tool generates a single string of up to 4,096 characters, with the same unbiased sampling at every length. Length and alphabet multiply together: 24 letters and digits carry about 143 bits, which is already more than any brute-force attack can reach, while 64 characters carry about 381 bits. Past roughly 128 bits a longer secret stops adding practical security and starts adding only size, so match the length to the job. The 64 character string generator and the entropy calculator show the arithmetic for any combination.

What makes a secure random string generator

Two things, and most generators get at least one of them wrong. The first is the source. A secure random string generator reads from a cryptographically secure random number generator: crypto.getRandomValues() in the browser, which draws from the operating system. Many online tools still use Math.random(), which is fast and fine for games but predictable to anyone who observes a few outputs. That is explained in detail in why Math.random() is not secure.

The second is the mapping. Taking a random number modulo the alphabet size makes some characters more likely than others, and this generator removes that by rejection sampling, as described below and in modulo bias explained. The statistical tests that confirm it are published on the methodology page, next to a deliberately broken implementation that the same tests catch.

Random string generator online, or in your own code

An online random string generator is the quickest option when you need a value now: a secret for a .env file, a test fixture, a one-off password. When the string has to be created inside an application at runtime, generate it in that language instead of pasting it in. The short version for each platform is below, and every name links to a full guide whose code was run on the real runtime:

Choosing between random string generator tools

Most random string generator tools look alike, so judge them on what you can check. Does the value get made in your browser, or sent back from a server where it can be logged? Does the site say which random source it uses? Does the strength figure fall when you require every character type, as it should? Can you exclude look-alike characters such as 0 O 1 l I for strings people have to read? Open your browser devtools, switch to the Network tab and press Generate: on this site nothing appears. For more specialised jobs, see the bulk random string generator, the custom character generator, the password generator, or every generator on the site.

How this generator works

Every value comes from crypto.getRandomValues(), the browser's interface to the operating system's cryptographic random number generator. There is no fallback: if a browser cannot provide a secure source, this tool refuses to generate rather than quietly using a weaker one.

Turning those raw bits into characters is where most generators go wrong. The obvious approach, taking the remainder of a random number divided by the alphabet size, does not divide evenly and skews the output toward the characters at the start of the alphabet. Mapping a single byte onto 62 characters makes the first eight of them 1.25 times more likely than the other fifty-four. This tool discards the draws that fall in the incomplete final cycle, so every character is exactly equally likely.

The same care applies to the "require one of each type" option. Rather than forcing a digit into a fixed position, which leaves a visible pattern, the generator produces a whole candidate string and rejects it if it does not satisfy the constraint. Every valid string is equally likely, and the entropy readout drops to the true figure instead of the one the naive formula gives.

We publish the test results rather than asking you to take this on trust. Across 500,000 generated characters, the character-frequency chi-square test gives p = 0.673. The same battery run against a deliberately biased implementation catches it at chi-square = 3345 on 61 degrees of freedom, which is how we know the tests are sensitive enough for the clean result to mean anything. Read the full methodology.

Doing this in your own code

If you need this inside an application rather than in a browser tab, here is the correct way to do it in each language. Each one uses that platform's cryptographic source and an unbiased mapping.

JavaScript (browser and Node 19+)
const ALPHABET = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";

function randomString(length) {
  const n = ALPHABET.length;
  // Largest multiple of n that fits in a uint32. Values at or above this
  // are discarded, which is what removes the modulo bias.
  const limit = Math.floor(2 ** 32 / n) * n;
  const out = new Array(length);
  const buf = new Uint32Array(length);
  crypto.getRandomValues(buf);

  for (let i = 0, j = 0; i < length; i++) {
    let v = buf[j++];
    while (v >= limit) {
      // Refill one word at a time on the rare rejection.
      const extra = new Uint32Array(1);
      crypto.getRandomValues(extra);
      v = extra[0];
    }
    out[i] = ALPHABET[v % n];
  }
  return out.join("");
}

randomString(24);

crypto.getRandomValues() refuses a single request over 65536 bytes, so a large batch has to be chunked.

Python 3.6+
import secrets
import string

ALPHABET = string.ascii_letters + string.digits

def random_string(length: int) -> str:
    # secrets.choice() is unbiased: it uses randbelow(), which is itself
    # rejection sampling over os.urandom. Do not use random.choice() here,
    # which is a Mersenne Twister and is not cryptographically secure.
    return "".join(secrets.choice(ALPHABET) for _ in range(length))

random_string(24)

secrets has been in the standard library since 3.6. Anything using the random module is the wrong tool for a secret.

Go
package main

import (
	"crypto/rand"
	"math/big"
)

const alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"

func randomString(length int) (string, error) {
	out := make([]byte, length)
	max := big.NewInt(int64(len(alphabet)))
	for i := range out {
		// rand.Int is unbiased; it rejects internally.
		n, err := rand.Int(rand.Reader, max)
		if err != nil {
			return "", err
		}
		out[i] = alphabet[n.Int64()]
	}
	return string(out), nil
}

crypto/rand, never math/rand. Go 1.20 seeds the math/rand global generator randomly on its own, which improves nothing about its predictability.

Rust
// rand = "0.9"
use rand::Rng;
use rand::distr::{Alphanumeric, SampleString};

fn random_string(length: usize) -> String {
    // rand::rng() is a thread-local ChaCha12 CSPRNG, seeded from the
    // operating system and reseeded periodically.
    // Alphanumeric samples uniformly over A-Z a-z 0-9.
    Alphanumeric.sample_string(&mut rand::rng(), length)
}

// With an arbitrary alphabet, random_range rejection-samples:
fn random_from(alphabet: &[u8], length: usize) -> String {
    let mut rng = rand::rng();
    (0..length)
        .map(|_| alphabet[rng.random_range(0..alphabet.len())] as char)
        .collect()
}

On rand 0.8 the paths differ: rand::distributions instead of rand::distr, DistString instead of SampleString, gen_range instead of random_range, and rand::thread_rng() instead of rand::rng().

PHP 7+
<?php
function randomString(int $length): string {
    $alphabet = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
    $n = strlen($alphabet);
    $out = '';
    for ($i = 0; $i < $length; $i++) {
        // random_int() is unbiased and cryptographically secure.
        // rand() and mt_rand() are neither.
        $out .= $alphabet[random_int(0, $n - 1)];
    }
    return $out;
}

echo randomString(24);
Java 17+
import java.security.SecureRandom;

public final class RandomString {
    private static final String ALPHABET =
        "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
    private static final SecureRandom RANDOM = new SecureRandom();

    public static String generate(int length) {
        StringBuilder sb = new StringBuilder(length);
        for (int i = 0; i < length; i++) {
            // nextInt(bound) rejects internally, so it is unbiased.
            sb.append(ALPHABET.charAt(RANDOM.nextInt(ALPHABET.length())));
        }
        return sb.toString();
    }
}

SecureRandom, not java.util.Random and not Math.random(), both of which are 48-bit linear congruential generators.

C# / .NET 6+
using System.Security.Cryptography;

public static class RandomStringGenerator
{
    private const string Alphabet =
        "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";

    public static string Generate(int length)
    {
        // GetString was added in .NET 8 and is unbiased.
        return RandomNumberGenerator.GetString(Alphabet, length);
    }

    // On .NET 6 and 7, GetInt32 is the unbiased primitive:
    public static string GenerateLegacy(int length)
    {
        var chars = new char[length];
        for (int i = 0; i < length; i++)
            chars[i] = Alphabet[RandomNumberGenerator.GetInt32(Alphabet.Length)];
        return new string(chars);
    }
}
C++11 and later
#include <random>
#include <string>

std::string random_string(std::size_t length) {
    static const std::string alphabet =
        "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";

    // uniform_int_distribution is specified to give every value in the range
    // equal probability, so there is no modulo bias to remove by hand.
    std::random_device rd;
    std::uniform_int_distribution<std::size_t> pick(0, alphabet.size() - 1);

    std::string out;
    out.reserve(length);
    for (std::size_t i = 0; i < length; ++i) {
        out += alphabet[pick(rd)];
    }
    return out;
}

std::random_device reads the operating system source on libstdc++, libc++ and MSVC, but the standard allows it to be deterministic, and MinGW builds before GCC 9.2 were. Where a guarantee matters, use libsodium randombytes_uniform() instead. Never std::rand() or std::mt19937 for a secret.

PowerShell 7
$chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789'

# GetInt32 draws from the OS CSPRNG and rejection samples internally.
-join (1..24 | ForEach-Object {
  $chars[[System.Security.Cryptography.RandomNumberGenerator]::GetInt32($chars.Length)]
})

Windows PowerShell 5.1 runs on .NET Framework, which has no GetInt32. There, pick each character with Get-Random -Maximum $chars.Length, which draws from the system CSPRNG unless -SetSeed is given. Avoid Get-Random -Count, which never repeats a character.

Shell
# 24 alphanumeric characters from the kernel CSPRNG.
LC_ALL=C tr -dc 'A-Za-z0-9' < /dev/urandom | head -c 24; echo

# Base64, URL-safe, from 32 bytes of entropy.
openssl rand -base64 32 | tr '+/' '-_' | tr -d '='

tr discards bytes outside the set rather than folding them into it, so this pipeline is unbiased. Putting `head -c 24` before `tr` instead gives you the alphanumeric subset of 24 raw bytes, which is a shorter and variable-length string, not 24 characters.

Full guides with tokens, passwords, bulk generation and the common mistakes in each language, with every example run on the real runtime:

Choosing a length

Length only means something alongside the alphabet. A string of 20 digits carries about 66 bits; 20 characters drawn from the 62 letters and digits carries 119. The table below is the number of characters you need to reach a given strength, and the generator shows the exact figure for whatever you have selected.

Alphabet Bits/char 64 bits 112 bits 128 bits
Digits only (10) 3.3219 20 34 39
Lowercase letters (26) 4.7004 14 24 28
Hex (16) 4.0000 16 28 32
Letters and digits (62) 5.9542 11 19 22
Look-alikes excluded (49) 5.6147 12 20 23
With safe symbols (74) 6.2095 11 19 21

Excluding look-alike characters costs 0.3395 bits per character, or 5.70%. One extra character every seventeen buys it back, which is usually worth it for anything a person has to read aloud or retype.

Questions

What is a random string generator?

A random string generator is a tool that builds a string by picking each character by chance from an alphabet, such as letters, digits and symbols. A good one uses a cryptographically secure random source and gives every character exactly the same probability, so the result cannot be predicted or reproduced.

What is a random string used for?

Random strings are used as API keys, session tokens, password reset and email verification links, CSRF tokens, passwords, encryption and signing secrets, database and file identifiers, coupon and invite codes, and test data for checking how an application handles input of a given length.

Is it safe to use an online random string generator?

It is safe when the string is generated in your browser and never sent anywhere, and when the tool uses a secure random source. You can check this site yourself: open the Network tab in your browser devtools and press Generate, and no request appears. A generator that creates the value on a server has to send it to you, so it could be logged along the way.

Is this random string generator online and free to use?

Yes. It is free, there is no account, no limit on how often you use it and no restriction on commercial use. It runs online in your browser, and once the page has loaded it keeps working offline as well.

How do I use the random string generator with special characters?

Turn on the !#$% toggle. That adds twelve symbols, ! # $ % * + - = ? @ ^ _, which almost every password policy accepts and which do not break shell commands or URLs. For a different set of symbols, type the exact alphabet you want into the custom character set field under More options.

How do I use this as a long random string generator?

Type the length into the number box next to the slider. The slider goes to 128, but the box accepts any length up to 4,096 characters. The entropy readout updates as you type, so you can see when the string is long enough for its purpose.

How do I generate a random alphanumeric string?

Leave the A-Z, a-z and 0-9 toggles on and the symbols toggle off, which is the default. That gives an alphabet of 62 characters, about 5.95 bits per character, so a 24-character string carries about 143 bits. For letters only, turn off 0-9; for numbers only, turn off both letter toggles.

Can I generate multiple random strings at once?

Yes. Open More options and set a quantity of up to 10,000. The results can be shown one per line, comma separated, as a JSON array, as a quoted list or as .env assignments, and copied or downloaded as a file. Tick "All results must be different from each other" if the batch has to contain no duplicates.

Are random strings unique?

Not by guarantee, but a long enough string is unique in practice. Duplicates follow the birthday bound: with about 143 bits, which is 24 letters and digits, you would need to generate around 2^71 strings before a repeat becomes likely. Short strings are different; a 6-character code repeats far sooner, so check uniqueness in your database when the string is short.

What makes a secure random string generator?

A cryptographically secure random source, such as crypto.getRandomValues() in the browser, and an unbiased mapping from random numbers to characters. A generator built on Math.random() is predictable, and one that uses the remainder operator without rejection sampling makes some characters more likely than others. This tool does neither, and publishes the test results.

What is the safest random string generator Python offers?

The secrets module: "".join(secrets.choice(string.ascii_letters + string.digits) for _ in range(24)). secrets.choice is cryptographically secure and unbiased. Do not use random.choice, which is a Mersenne Twister and can be predicted from its output. The Python random string generator guide on this site adds tokens, passwords and unique IDs, all run on Python 3.14.

What is the right random string generator Java code should use?

Create one java.security.SecureRandom and call nextInt(alphabet.length()) for each character, appending alphabet.charAt() to a StringBuilder. nextInt with a bound is unbiased. Do not use java.util.Random or Math.random(), which are both predictable 48-bit generators. The Java random string generator guide also shows what Apache Commons RandomStringUtils uses in each release.

How do I build a random string generator JavaScript can run in the browser?

Fill a Uint32Array with crypto.getRandomValues(), discard values at or above the largest multiple of the alphabet size, and index into the alphabet with the rest. It works in every modern browser and in Node.js 19 and later. The full function is in the code examples on this page, and the JavaScript random string generator guide has tested browser and Node.js versions. Math.random() is not secure for this.

How do I write a random string generator C++ code can rely on?

Use std::uniform_int_distribution over std::random_device and index into your alphabet. The distribution is unbiased by specification. std::random_device reads the operating system source on the major compilers, but the standard does not guarantee it, so use libsodium randombytes_uniform() where that matters. Avoid std::rand(). The C++ random string generator guide includes a Windows version built on BCryptGenRandom.

Is there a built-in random string generator PHP provides?

Yes. On PHP 8.3 and later, (new Random\Randomizer())->getBytesFromString($alphabet, $length) does it in one call. On older versions, call random_int(0, strlen($alphabet) - 1) for each character and append the character at that index; random_int is cryptographically secure, unbiased and built in since PHP 7. Do not use rand(), mt_rand() or str_shuffle() for anything secret. The PHP random string generator guide shows why.

Does .NET have a random string generator C# code can call directly?

Yes, on .NET 8 and later: RandomNumberGenerator.GetString(alphabet, length) is secure and unbiased in one line. On .NET 6 and 7, call RandomNumberGenerator.GetInt32(alphabet.Length) for each character. System.Random is not suitable for secrets. The C# random string generator guide covers tokens and passwords as well.

How do I make a PowerShell random string generator?

On PowerShell 7.4 and later, call [System.Security.Cryptography.RandomNumberGenerator]::GetString($chars, 24). On Windows PowerShell 5.1, which lacks that method, append $chars[(Get-Random -Maximum $chars.Length)] once per character. Get-Random draws from the system cryptographic generator unless you pass -SetSeed. Avoid Get-Random -Count, which never repeats a character. The PowerShell random string generator guide has scripts that were run on both versions.

How do I build a JS random string generator in Node.js?

For a hex or URL-safe string, use crypto.randomBytes(16).toString("hex") or crypto.randomBytes(18).toString("base64url"). For a custom alphabet, pick each character with crypto.randomInt(alphabet.length), which is secure and unbiased. Do not build secrets from Math.random().

How do I generate a random string in Linux or Bash?

Run LC_ALL=C tr -dc "A-Za-z0-9" < /dev/urandom | head -c 24 for 24 letters and digits, or openssl rand -hex 16 for a 32-character hex string. Both read the kernel random source. Avoid $RANDOM, which is a 15-bit value from a non-cryptographic generator.

How do I generate a random string in Go?

Use crypto/rand. From Go 1.24, rand.Text() returns a 26-character Base32 string with at least 128 bits of randomness. For your own alphabet, pick each character with rand.Int(rand.Reader, big.NewInt(int64(len(alphabet)))). Never use math/rand for secrets.

How do I generate a random string in Excel?

In Excel 365, =TEXTJOIN("",TRUE,CHAR(RANDARRAY(10,1,65,90,TRUE))) gives 10 random uppercase letters, and it changes every time the sheet recalculates. Excel random functions are not cryptographically secure, so use this for test data only, and generate passwords or keys with a secure tool instead.

Is anything I generate sent to a server?

No. Generation runs entirely in your browser using the Web Crypto API. There is no backend to send it to, and you can confirm that yourself: open your browser devtools, switch to the Network tab, and press Generate. Nothing appears.

What makes this different from using Math.random()?

Math.random() is not cryptographically secure. V8 implements it with xorshift128+, a 128-bit non-cryptographic generator, and the JavaScript specification does not require its output to be unpredictable. Published work shows that an observer who sees a handful of outputs can recover the internal state and reproduce every past and future value. This tool uses crypto.getRandomValues(), which draws from the operating system CSPRNG.

What is modulo bias, and does this tool have it?

Reducing a random number with the remainder operator skews the result toward the start of the alphabet. Mapping a byte onto 62 characters gives 256 = 4x62 + 8, so the first eight characters are 1.25 times more likely than the rest. This tool removes it with rejection sampling: draws that fall in the incomplete final cycle are discarded rather than folded in.

Why does the entropy figure drop when I require every character type?

Because it should. Requiring at least one digit forbids every string that has no digit, so there are fewer possible outputs and the true entropy is lower than length x log2(alphabet size). Most generators keep printing the higher number. This one counts the valid strings by inclusion-exclusion and shows the real figure, with the unconstrained number in brackets so you can see the cost.

How long should a random string be?

It depends on what it protects. For a value an attacker can only guess online against a rate-limited endpoint, 64 bits is comfortable. For a secret that could be captured and attacked offline, aim for 112 bits or more; 19 alphanumeric characters reaches 113 bits. For a password, NIST SP 800-63B requires a minimum of 15 characters and explicitly recommends against composition rules.

Can I use this for passwords, API keys and session tokens?

Yes. The randomness source is the same one your operating system offers to any application, and the mapping onto characters is unbiased. What the tool cannot do is protect the value after it leaves this page, so treat the result the way you would treat any other secret.

Speed

10,000 strings of 32 characters take 17 ms to generate. Large batches are produced in chunks with the main thread released between each one, so the page stays responsive and the run can be cancelled. Three of the generators currently ranking on page one of Google have no quantity limit at all and freeze the tab instead.