Back to Blog
Random Strings, Tokens and API Keys: A Practical Guide
Aug 04, 2026 7 min read 4,790 views Admin

Random Strings, Tokens and API Keys: A Practical Guide

sk_live_51Hx7aQ9mK2pLxVw... — strings like this guard the gates of the modern internet. API keys, session tokens, password-reset links, and verification codes are all random strings: unpredictable sequences of characters that prove identity or grant access. If you've ever built anything with a login system or an API, you've needed them. This guide explains what they are, how to make them properly, and the mistakes that make them useless.

What Are Random Strings Used For?

A random string is a sequence of characters chosen unpredictably, used as a secret or identifier that shouldn't be guessable. The main uses:

  • API keys. Credentials that let one application talk to another — Stripe, OpenAI, Google Maps all issue them. They look like sk-... or long hex strings and are passed with each request to prove who's calling.
  • Session tokens. When you log into a website, the server gives your browser a random token (usually in a cookie). Presenting that token on each page load proves you're still logged in, without re-entering your password.
  • Password-reset tokens. The link in a "reset your password" email contains a random token. Whoever holds the link can reset the password — so the token must be unguessable and expire quickly.
  • Temporary passwords and verification codes. One-time codes sent by SMS or email (like 482913) are short random strings with a short lifetime.
  • Nonces. "Number used once" — a random value attached to a request to prevent replay attacks, where an attacker re-sends a captured request.
  • CSRF tokens. Random values embedded in web forms to prove the submission came from your site, not a malicious page tricking your browser.

The common thread: in every case, the string's security comes from being unpredictable. If an attacker can guess or predict it, the protection collapses.

Randomness vs. Pseudo-Randomness, in Plain Language

True randomness comes from unpredictable physical processes — atmospheric noise, precise mouse movements, hardware circuits that measure quantum effects. Computers mostly can't do this on demand, so they use pseudo-random number generators (PRNGs): algorithms that produce sequences that look random.

The critical distinction:

  • Regular PRNGs (like Math.random() in JavaScript or random in Python) are designed for simulations and games. They're fast, but their output can be predicted if an attacker learns enough of the sequence. Never use these for security tokens.
  • Cryptographically secure PRNGs (CSPRNGs) (like crypto.getRandomValues() in browsers, Python's secrets module, or /dev/urandom on Linux) are designed so that observing past output gives no useful information about future output. Always use these for tokens, keys, and passwords.

Rule of thumb: if the string protects anything — an account, money, data — use the cryptographic generator your platform provides. The regular one is for shuffling playlists and spawning game enemies.

How Length and Character Set Affect Strength

A token's strength is measured in bits of entropy — roughly, how many guesses an attacker would need in the worst case. The formula:

entropy bits = length × log₂(alphabet size)

Some concrete numbers:

Format                    | Example           | Entropy
--------------------------|-------------------|-------------------------------
6-digit SMS code          | 482913            | ~20 bits (1 million possibilities)
8-char lowercase password | xkqzmwpv          | ~38 bits
16-char alphanumeric      | aB3dE9fH2jK5mN7p | ~95 bits
32 hex chars (128-bit)    | 9f2c... (32 chars)| 128 bits
43-char base64 (256-bit)  | dGhpcyBpcyBh...   | 256 bits

What these numbers mean in practice:

  • ~20 bits (SMS codes): guessable in theory, but protected by short expiry (5–10 minutes) and rate limiting (3–5 attempts). Never rely on a short code alone without those protections.
  • ~80+ bits: beyond brute force for any realistic attacker. A 16-character random alphanumeric string is already here.
  • 128 bits: the standard for session tokens and API keys. Brute-forcing 2¹²⁸ possibilities is physically infeasible — it would take longer than the age of the universe with all Earth's computing power.
  • 256 bits: used for encryption keys. Overkill for tokens, but harmless.

Length beats complexity. A 20-character all-lowercase random string (~94 bits) is stronger than an 8-character mixed-symbol password (~52 bits) — and easier to type. When generating tokens, prefer longer strings from a simple alphabet over short strings from a huge alphabet.

Generating Random Strings: Practical Examples

In code (the right way)

Python:

import secrets
token = secrets.token_hex(32)      # 64 hex chars, 256 bits
url_token = secrets.token_urlsafe(32)  # URL-safe, for reset links

JavaScript (browser or Node):

const bytes = crypto.getRandomValues(new Uint8Array(32));
const token = [...bytes].map(b => b.toString(16).padStart(2, '0')).join('');

The pattern is the same everywhere: call the platform's cryptographic random function, get random bytes, encode them as hex or base64.

For one-off needs

For a quick API key, test token, or temporary password, an online random string generator — like the free one on Converters Online — is perfect: choose the length and character set (letters, digits, symbols), click generate, copy the result. Just make sure the tool uses a cryptographically secure source of randomness (reputable ones do).

Choosing a format

  • Hex (9f2ca1...): simple, universally safe in URLs and configs, but 2× longer than the raw bytes.
  • Base64url (xK2_9pLm...): ~33% shorter than hex, URL-safe variant avoids + and /.
  • Alphanumeric: good for codes humans might type.
  • With symbols: fine for passwords stored by managers, annoying for anything typed by hand.

Storing and Handling Tokens Safely

Generating a strong token is only half the job:

  • Treat tokens like passwords. API keys and reset tokens are secrets. Don't commit them to git, paste them into chat logs, or leave them in screenshots.
  • Hash tokens before storing. If your database leaks, stored plaintext tokens give attackers instant access. Store a SHA-256 hash of the token and compare hashes — exactly like password storage (though tokens, unlike passwords, are already high-entropy, so plain hashing without salt is acceptable).
  • Set expirations. Reset tokens: 15–60 minutes. Session tokens: hours to days, with renewal. API keys: no expiry by default, but support revocation.
  • Make them revocable. Every API key system needs a "delete this key" button. A leaked key you can't revoke is a permanent breach.
  • Use one token per purpose. Don't reuse the same random string as both a session token and a CSRF token — separate concerns, separate tokens.

Common Mistakes

  • Using Math.random() for security. The single most common token bug. It's predictable. Use crypto.getRandomValues() / secrets / /dev/urandom.
  • Too short. A 4-digit code with no rate limiting falls in seconds. Match length to the threat: short codes need expiry + attempt limits; long tokens stand alone.
  • Predictable "random" IDs. Sequential IDs, timestamps, or usernames hashed with MD5 are not random. If it can be enumerated, it's not a secret.
  • Logging tokens. Tokens in server logs, error reports, or analytics become plaintext secrets sitting in a third-party system. Redact them.
  • Never expiring reset links. A password-reset token from 2019 should not work today. Expire aggressively.
  • Emailing API keys in plaintext and then never rotating them. If a key was ever transmitted insecurely, rotate it.

Frequently Asked Questions

Q: How long should an API key be? A: 128 bits of entropy is the standard — that's 32 hex characters or about 22 base64 characters. Longer is fine; shorter than 80 bits is asking for trouble.

Q: Is Math.random() really that bad for tokens? A: Yes. Its output is deterministic given the internal state, and the state can be reconstructed from observed outputs. There are public tools that do exactly this. For anything security-related, always use a cryptographically secure generator.

Q: Should I hash API keys in my database? A: Yes. Store a SHA-256 hash, not the raw key — show the key to the user once at creation, then never again. This way a database breach doesn't hand attackers working keys.

Q: What's the difference between a token and a password? A: A password is chosen (or at least known) by a human and reused across sessions; a token is generated by the system, high-entropy, and usually scoped and expirable. Tokens are machine credentials; passwords are human credentials.

Q: Can I just use a UUID as a token? A: A version 4 UUID has 122 bits of randomness from a CSPRNG — that's fine entropy-wise for many token uses. Just make sure your UUID library uses a secure random source (most do), and still apply expiry and hashing practices.

Related Articles

Try Our Free Tools



Share:
#random string generator #api key #secure token #entropy #secrets

Comments (0)

Leave a Comment

No comments yet. Be the first to share your thoughts!
Support Chat
We typically reply within minutes

Hello! 👋 Before we start, please tell us your name.