Random String Code Examples
Alphanumeric, hex and URL-safe strings in PHP, JavaScript, Python, Java, C#, C++, Ruby and Go
Every example below builds the same three strings: 16 alphanumeric characters, 12 hex characters and 10 lowercase letters, from one function that accepts a custom alphabet. Several languages also show a one-call shortcut for hex or URL-safe tokens. The guide explains how alphabet and length decide strength, and which character sets survive URLs, filenames and humans. Prefer no code? The interactive Strings generator does the same in the browser.
Alphabet size and length decide the strength
A random string is a sequence of independent picks from an alphabet. Each character adds log2(alphabet size) bits: 4 bits for hex (16 symbols), 4.7 for lowercase letters (26), about 5.95 for alphanumeric (62) and exactly 6 for base64url (64). The 16-character alphanumeric string in the examples therefore carries about 95 bits, the 12-character hex string 48 bits and the 10-letter lowercase string 47 bits.
For a token that an attacker might try to guess, aim for at least 128 bits: 32 hex characters, 22 alphanumeric characters or 22 base64url characters. For an identifier that only has to avoid collisions, size it with the birthday bound: with b bits, a duplicate becomes likely after about 2b/2 strings, so 48 bits (12 hex characters) already risks a collision after roughly 16 million values.
Encoding bytes versus picking characters
There are two ways to build the string. Encoding random bytes (hex, base64, base32) is fast and exact: 16 bytes become 32 hex characters or 22 base64url characters with no bias. Picking each character from an alphabet by index is the only way to use an arbitrary set, such as letters without vowels, but the index must be uniform. Library calls that take a bound (random_int, secrets.choice, SecureRandom.nextInt, crypto/rand.Int) are exactly uniform; taking a random 32-bit value modulo the alphabet length, as the JavaScript and C# examples do, is off by less than one part in 69 million for 62 symbols, which is negligible, but the same trick on a single byte skews the first characters noticeably.
When the string must be secure
If the string grants access (a session ID, a password-reset or email-verification link, an invitation code, a CSRF token), draw it from the cryptographic source: random_bytes/random_int, crypto.getRandomValues, secrets, SecureRandom, RandomNumberGenerator or crypto/rand. If it only has to be different, such as a temporary filename, a cache-busting suffix or a fixture name in a test, the fast generator is enough, and a fixed seed makes test output reproducible. All examples on this page use the secure source, so they are safe for both.
Common mistakes
- Hashing the time.
md5(time())or a hash of a counter looks random but has only as many possibilities as the input; anyone who knows the minute can enumerate them. - Confusing bytes and characters.
bin2hex(random_bytes(16))is 32 characters, andtoken_urlsafe(16)is 22. Size the call by the entropy you want, not by the length you see. - Plain base64 in URLs. Standard base64 contains
+,/and=, which must be percent-encoded in query strings and break in filenames. Use the base64url alphabet (-and_, no padding). - Look-alike characters for humans. Codes that people read aloud or type should drop
0/O,1/l/Iand often5/S; Crockford base32 is a ready-made 32-symbol alphabet built for this. - Case-insensitive storage. An alphanumeric token compared in a case-insensitive database column (the MySQL default collations) drops from 62 to 36 effective symbols, about 0.8 bits per character.
Common Use Cases
- Session IDs, CSRF tokens and password-reset or verification links
- API keys and client secrets
- Non-sequential public identifiers for database records and short links
- Unique names for uploaded files, temporary files and cache keys
- Correlation and request IDs across microservices
- Invitation, coupon and voucher codes
Random String Code Examples in PHP
Generate random strings in PHP using random_bytes() for cryptographically secure random data. Perfect for tokens, IDs, and secure string generation.
<?php
// Generate a random alphanumeric string
function generateRandomString($length = 16, $customChars = null) {
if ($customChars !== null) {
// Use custom character set
$chars = $customChars;
$result = '';
$charsLength = strlen($chars);
for ($i = 0; $i < $length; $i++) {
$randomIndex = random_int(0, $charsLength - 1);
$result .= $chars[$randomIndex];
}
return $result;
}
// Default: generate hex string from random bytes
$bytes = random_bytes(ceil($length / 2));
return substr(bin2hex($bytes), 0, $length);
}
// Generate a 16-character hex string
$hexString = generateRandomString(16);
echo $hexString; // Example: a3f7b2e9c4d1f8a6
// Generate a 12-character alphanumeric string
$alphanumeric = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
$customString = generateRandomString(12, $alphanumeric);
echo $customString; // Example: aB3xY7mN2pQ9
How it works in PHP
This function uses random_bytes() to generate cryptographically secure random data. When no custom character set is provided, it uses bin2hex() for efficient hex string generation. For custom character sets, it uses random_int() for secure index selection.
Sample output
a3f7b2e9c4d1f8a6 aB3xY7mN2pQ9
PHP notes
bin2hex(random_bytes($n))returns 2n hex characters; the default branch of the example halves the length for that reason.- PHP 8.3+
(new Random\Randomizer())->getBytesFromString($alphabet, $length)picks characters from any alphabet in one call. - For URL-safe tokens:
rtrim(strtr(base64_encode(random_bytes(16)), '+/', '-_'), '=').
Random String Code Examples in JavaScript
Generate random strings in JavaScript using crypto.getRandomValues() for cryptographically secure random values. Works in browsers and Node.js.
function generateRandomString(length = 16, customChars = null) {
const defaultChars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
const chars = customChars || defaultChars;
const array = new Uint32Array(length);
crypto.getRandomValues(array);
let result = '';
for (let i = 0; i < length; i++) {
result += chars[array[i] % chars.length];
}
return result;
}
// Generate a 16-character alphanumeric string
const randomString = generateRandomString(16);
console.log(randomString); // Example: aB3xY7mN2pQ9zR5t
// Generate a 12-character hex string
const hexChars = '0123456789abcdef';
const hexString = generateRandomString(12, hexChars);
console.log(hexString); // Example: a3f7b2e9c4d1
// Generate a 10-character lowercase string
const lowercaseString = generateRandomString(10, 'abcdefghijklmnopqrstuvwxyz');
console.log(lowercaseString); // Example: xmkpqrstuv
How it works in JavaScript
The function fills a Uint32Array with crypto.getRandomValues(), one cryptographically secure 32-bit value per character, and maps each value onto the alphabet with the modulo operator. With 32-bit values the resulting bias is under one part in 69 million for a 62-character alphabet, which is negligible. Pass any string as the second argument to change the alphabet.
Sample output
aB3xY7mN2pQ9zR5t a3f7b2e9c4d1 xmkpqrstuv
JavaScript notes
- Node.js 19+ has a global
crypto; on older versions userequire('node:crypto').webcrypto.getRandomValuesorcrypto.randomBytes(16).toString('base64url')(Node 15.7+). chars[i]indexes UTF-16 code units, so an alphabet with emoji or other astral characters needsArray.from(chars)first.Math.random().toString(36).slice(2)is a common shortcut but gives a variable length and is not secure.
Random String Code Examples in Python
Generate random strings in Python using the secrets module for cryptographically secure random generation. Perfect for tokens, IDs, and security-sensitive applications.
import secrets
import string
def generate_random_string(length=16, custom_chars=None):
if custom_chars is None:
# Default: alphanumeric characters
custom_chars = string.ascii_letters + string.digits
return ''.join(secrets.choice(custom_chars) for _ in range(length))
# Generate a 16-character alphanumeric string
random_string = generate_random_string(16)
print(random_string) # Example: aB3xY7mN2pQ9zR5t
# Generate a 12-character hex string
hex_string = generate_random_string(12, string.hexdigits[:16])
print(hex_string) # Example: a3f7b2e9c4d1
# Generate a 10-character lowercase string
lowercase_string = generate_random_string(10, string.ascii_lowercase)
print(lowercase_string) # Example: xmkpqrstuv
# Generate URL-safe token (alternative method)
url_safe_token = secrets.token_urlsafe(16)
print(url_safe_token) # Example: xK8mP2vN5qR7sT9w
How it works in Python
The secrets module provides cryptographically strong random string generation. secrets.choice() securely selects random characters. The string module provides convenient character sets. For URL-safe tokens, use secrets.token_urlsafe().
Sample output
aB3xY7mN2pQ9zR5t a3f7b2e9c4d1 xmkpqrstuv xK8mP2vN5qR7sT9w
Python notes
secrets.token_hex(16)returns 32 hex characters andsecrets.token_urlsafe(16)about 22 base64url characters: the argument is bytes.string.hexdigitsis0123456789abcdefABCDEF, so the example slices the first 16 to avoid doubling the weight of a–f.random.choices(alphabet, k=16)is shorter but uses Mersenne Twister; keep it for test data.
Random String Code Examples in Java
Generate random strings in Java using SecureRandom for cryptographically secure random generation. Suitable for enterprise applications and security-critical systems.
import java.security.SecureRandom;
public class RandomStringGenerator {
private static final String ALPHANUMERIC =
"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
private static final String HEX_CHARS = "0123456789abcdef";
public static String generateRandomString(int length, String customChars) {
SecureRandom random = new SecureRandom();
String chars = (customChars != null) ? customChars : ALPHANUMERIC;
StringBuilder result = new StringBuilder(length);
for (int i = 0; i < length; i++) {
int index = random.nextInt(chars.length());
result.append(chars.charAt(index));
}
return result.toString();
}
public static void main(String[] args) {
// Generate a 16-character alphanumeric string
String randomString = generateRandomString(16, null);
System.out.println(randomString); // Example: aB3xY7mN2pQ9zR5t
// Generate a 12-character hex string
String hexString = generateRandomString(12, HEX_CHARS);
System.out.println(hexString); // Example: a3f7b2e9c4d1
// Generate a 10-character lowercase string
String lowercaseString = generateRandomString(10, "abcdefghijklmnopqrstuvwxyz");
System.out.println(lowercaseString); // Example: xmkpqrstuv
}
}
How it works in Java
SecureRandom provides cryptographically strong random number generation. StringBuilder is used for efficient string construction. The method accepts custom character sets for flexible string generation.
Sample output
aB3xY7mN2pQ9zR5t a3f7b2e9c4d1 xmkpqrstuv
Java notes
- Create one
SecureRandomand reuse it; it is thread-safe, and a new instance per call costs a seeding step. - For hex,
HexFormat.of().formatHex(bytes)(Java 17+); for URL-safe,Base64.getUrlEncoder().withoutPadding(). UUID.randomUUID().toString()is 36 characters but only 122 random bits; it is not a shorter token.
Random String Code Examples in C#
Generate random strings in C# using RandomNumberGenerator for cryptographically secure random data. Perfect for ASP.NET and .NET applications.
using System;
using System.Security.Cryptography;
using System.Text;
class RandomStringGenerator
{
private const string Alphanumeric =
"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
private const string HexChars = "0123456789abcdef";
public static string GenerateRandomString(int length, string customChars = null)
{
string chars = customChars ?? Alphanumeric;
using (var rng = RandomNumberGenerator.Create())
{
var result = new StringBuilder(length);
byte[] randomBytes = new byte[length * 4];
rng.GetBytes(randomBytes);
for (int i = 0; i < length; i++)
{
uint randomValue = BitConverter.ToUInt32(randomBytes, i * 4);
result.Append(chars[(int)(randomValue % chars.Length)]);
}
return result.ToString();
}
}
static void Main()
{
// Generate a 16-character alphanumeric string
string randomString = GenerateRandomString(16);
Console.WriteLine(randomString); // Example: aB3xY7mN2pQ9zR5t
// Generate a 12-character hex string
string hexString = GenerateRandomString(12, HexChars);
Console.WriteLine(hexString); // Example: a3f7b2e9c4d1
// Generate a 10-character lowercase string
string lowercaseString = GenerateRandomString(10, "abcdefghijklmnopqrstuvwxyz");
Console.WriteLine(lowercaseString); // Example: xmkpqrstuv
}
}
How it works in C#
RandomNumberGenerator fills a buffer with cryptographically secure bytes, four per character. Each 4-byte group is read as an unsigned 32-bit value and reduced modulo the alphabet length, which leaves a bias under one part in 69 million for 62 characters. StringBuilder collects the characters.
Sample output
aB3xY7mN2pQ9zR5t a3f7b2e9c4d1 xmkpqrstuv
C# notes
- .NET 8+ does all of this in one call:
RandomNumberGenerator.GetString(alphabet, length), without bias. - On .NET Core 3.0+
RandomNumberGenerator.GetInt32(chars.Length)gives an unbiased index per character. Convert.ToHexString(RandomNumberGenerator.GetBytes(16))(.NET 6+) returns 32 uppercase hex characters.
Random String Code Examples in C++
Generate random strings in C++ using the modern <random> library with random_device for secure seeding. Works with C++11 and later.
#include <iostream>
#include <string>
#include <random>
const std::string ALPHANUMERIC =
"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
const std::string HEX_CHARS = "0123456789abcdef";
std::string generateRandomString(int length, const std::string& customChars = ALPHANUMERIC) {
std::random_device rd;
std::uniform_int_distribution<> distrib(0, customChars.length() - 1);
std::string result;
result.reserve(length);
for (int i = 0; i < length; ++i) {
result += customChars[distrib(rd)];
}
return result;
}
int main() {
// Generate a 16-character alphanumeric string
std::string randomString = generateRandomString(16);
std::cout << randomString << std::endl; // Example: aB3xY7mN2pQ9zR5t
// Generate a 12-character hex string
std::string hexString = generateRandomString(12, HEX_CHARS);
std::cout << hexString << std::endl; // Example: a3f7b2e9c4d1
// Generate a 10-character lowercase string
std::string lowercaseString = generateRandomString(10, "abcdefghijklmnopqrstuvwxyz");
std::cout << lowercaseString << std::endl; // Example: xmkpqrstuv
return 0;
}
How it works in C++
The function uses std::random_device directly as the engine for uniform_int_distribution, so each character index comes from the platform's non-deterministic source and is uniform over the alphabet. Seeding std::mt19937 with a single rd() call would limit every possible output to 232 sequences. reserve() allocates the result once.
Sample output
aB3xY7mN2pQ9zR5t a3f7b2e9c4d1 xmkpqrstuv
C++ notes
- The standard does not require
std::random_deviceto be non-deterministic; libstdc++ on Linux, libc++ and MSVC read the OS source, but old MinGW builds (before GCC 9.2) returned a fixed sequence. - For tokens in production, prefer an OS call (
getrandom(),BCryptGenRandom) or libsodium'srandombytes_uniform(). - For test data that only needs to differ, a reused
std::mt19937is much faster thanrandom_device.
Random String Code Examples in Ruby
Generate random strings in Ruby using SecureRandom for cryptographically secure random generation. Perfect for Ruby on Rails applications.
require 'securerandom'
def generate_random_string(length = 16, custom_chars = nil)
chars = custom_chars || ('a'..'z').to_a + ('A'..'Z').to_a + ('0'..'9').to_a
Array.new(length) { chars[SecureRandom.random_number(chars.length)] }.join
end
# Generate a 16-character alphanumeric string
random_string = generate_random_string(16)
puts random_string # Example: aB3xY7mN2pQ9zR5t
# Generate a 12-character hex string
hex_string = generate_random_string(12, ('0'..'9').to_a + ('a'..'f').to_a)
puts hex_string # Example: a3f7b2e9c4d1
# Generate a 10-character lowercase string
lowercase_string = generate_random_string(10, ('a'..'z').to_a)
puts lowercase_string # Example: xmkpqrstuv
# Alternative: use built-in methods
hex_token = SecureRandom.hex(8) # 16 hex characters
puts hex_token
urlsafe_token = SecureRandom.urlsafe_base64(12)
puts urlsafe_token
How it works in Ruby
SecureRandom.random_number provides cryptographically secure random integers. This implementation uses Ruby's idiomatic array and string methods. Built-in methods like SecureRandom.hex() and SecureRandom.urlsafe_base64() offer convenient alternatives.
Sample output
aB3xY7mN2pQ9zR5t a3f7b2e9c4d1 xmkpqrstuv a3f7b2e9c4d1f8a6 xK8mP2vN5qR7sT9w
Ruby notes
SecureRandom.alphanumeric(16)(Ruby 2.5+) builds the default case in one call; Ruby 3.3+ acceptschars:for a custom alphabet.SecureRandom.hex(n)returns 2n characters, andSecureRandom.urlsafe_base64(n)about 4n/3 without padding.Array#sampleandshuffleacceptrandom: SecureRandomwhen you pick from an array.
Random String Code Examples in Go
Generate random strings in Go using crypto/rand for cryptographically secure random generation. Perfect for microservices and backend systems.
package main
import (
"crypto/rand"
"fmt"
"math/big"
)
const (
alphanumeric = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
hexChars = "0123456789abcdef"
)
func generateRandomString(length int, customChars string) (string, error) {
if customChars == "" {
customChars = alphanumeric
}
result := make([]byte, length)
charsLen := big.NewInt(int64(len(customChars)))
for i := 0; i < length; i++ {
num, err := rand.Int(rand.Reader, charsLen)
if err != nil {
return "", err
}
result[i] = customChars[num.Int64()]
}
return string(result), nil
}
func main() {
// Generate a 16-character alphanumeric string
randomString, _ := generateRandomString(16, "")
fmt.Println(randomString) // Example: aB3xY7mN2pQ9zR5t
// Generate a 12-character hex string
hexString, _ := generateRandomString(12, hexChars)
fmt.Println(hexString) // Example: a3f7b2e9c4d1
// Generate a 10-character lowercase string
lowercaseString, _ := generateRandomString(10, "abcdefghijklmnopqrstuvwxyz")
fmt.Println(lowercaseString) // Example: xmkpqrstuv
}
How it works in Go
crypto/rand.Int() provides cryptographically secure random integers. This implementation properly handles errors and uses big.Int for secure index generation. The function accepts custom character sets for flexible string generation.
Sample output
aB3xY7mN2pQ9zR5t a3f7b2e9c4d1 xmkpqrstuv
Go notes
- Go 1.24+ adds
crypto/rand.Text(), which returns 26 base32 characters carrying 130 random bits. - Since Go 1.24
crypto/rand.Readnever returns an error; earlier versions should still check it. hex.EncodeToStringandbase64.RawURLEncoding.EncodeToStringturn random bytes into hex or URL-safe tokens.- Indexing a Go string returns bytes, so the example only works with ASCII alphabets; use a
[]runefor others.
Try the Interactive Generator
Need values right now rather than code? The Strings generator runs in the browser and exports to TXT, CSV or JSON.
OPEN THE STRINGS GENERATOR →