← Back to Blog

Stop Using Math.random() for Secrets: How to Generate Truly Random Strings

[ Ad Space 970×90 — AdSense ]

"Generate me a random string" sounds trivial. Open a tool, pick a length, click a button, copy the result. But there is a quiet split in the word "random" that most people never notice — and it decides whether your API key, coupon code, or password-reset token can be guessed by someone who has never seen your machine.

This guide is about that split, the one-line mistake that causes it, and how to generate random strings you can actually trust — without installing anything.

1. The 30-second version

Open the Random String Generator, set a length (1–128), tick the character sets you want — uppercase, lowercase, digits, symbols — and click Generate. Every string is produced with a cryptographically secure random source right in your browser, so nothing leaves your device. No signup, no server.

2. There are two kinds of "random"

When a human says "random," they usually mean "unpredictable." A computer often means something weaker: "spread out according to a pattern that looks even."

The trap is using the first kind where only the second kind is safe.

3. The trap: Math.random() is not secure

In JavaScript, Math.random() is a PRNG. In every major browser it is implemented as something like xorshift128+, seeded from the system clock at startup. Two consequences matter:

That is fine for Math.floor(Math.random() * 6) to roll a die in a game. It is not fine for:

A token generated with Math.random() is not a secret. It is a number someone can eventually guess — and guessing it may mean impersonating a user or redeeming someone else's discount.

4. The safe alternative: crypto.getRandomValues

The Web Crypto API exposes crypto.getRandomValues(), which draws from the operating system's cryptographically secure random source (on Linux/macOS typically /dev/urandom, on Windows BCryptGenRandom, in browsers backed by the OS CSPRNG). It is:

The Jisubao Random String Generator builds each character by calling crypto.getRandomValues and mapping the result into your chosen character set — the same source a browser uses internally to mint UUIDs and certificates. That is the difference between "looks random" and "provably hard to guess."

5. How to generate a safe string (and the wrong way)

The wrong way:

// UNSAFE for secrets — predictable PRNG
function badToken(n){
  const chars='ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
  let s='';
  for(let i=0;i<n;i++) s+=chars[Math.floor(Math.random()*chars.length)];
  return s;
}

The right way:

// SAFE — cryptographically secure
function goodToken(n){
  const chars='ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
  const arr=new Uint32Array(n);
  crypto.getRandomValues(arr);          // fill with secure random
  let s='';
  for(let i=0;i<n;i++) s+=chars[arr[i]%chars.length];
  return s;
}

That second snippet is, in essence, what the tool does when you click Generate — except it lets you toggle symbols and push the length up to 128.

6. How long is "long enough"?

Entropy is measured in bits. With a 62-character alphabet (upper + lower + digits), each character carries about log2(62) ≈ 5.95 bits. Rough guide:

Rule of thumb: 16 mixed-case alphanumeric characters is a sane default for a secret you actually care about. If the token gates money or accounts, prefer longer and add symbols. The Password Generator applies the same secure-source idea to full passphrases, and the UUID Generator gives you a standards-based v4 identifier when you need a unique ID rather than a secret.

7. When you do NOT need secure randomness

Using crypto.getRandomValues for everything is not wrong, but it is sometimes unnecessary and slightly slower. You can safely use Math.random() for:

If a bad actor guessing the value costs nobody anything, the fast PRNG is the right tool.

8. FAQ

Q: Is Math.random() ever okay for a token? — Only if the token protects nothing: a throwaway demo ID, a cache key, a nonce that is also signed and timestamped. The moment it is a secret (auth, discount, draw), use a secure source.

Q: Does a longer Math.random() string become safe? — No. Length does not fix predictability. A 64-character string from a PRNG is just a longer guessable string. Security comes from the source, not the length.

Q: Can I generate a secure random string on a plain http:// page? — Browsers only expose crypto.getRandomValues in secure contexts (HTTPS or localhost). On plain HTTP the secure API is blocked — one more reason ijisubao.cn is served over HTTPS.

Q: What about Node.js or Python? — Same principle: avoid Math.random / naive random for secrets. In Node use crypto.randomBytes; in Python use secrets.token_urlsafe. Both pull from the same OS CSPRNG family.

Q: What if I need to send the random string somewhere? — Generate it locally and transmit over HTTPS only. The Jisubao generator never uploads your output — it is computed in the page and copied by you. If you later store it, hash it (and consider Base64 only for transport, never for secrecy).

If the random string is a secret, generate it from a cryptographically secure source (crypto.getRandomValues, crypto.randomBytes, secrets), not Math.random(). Use the free Random String Generator to do exactly that in your browser — pick your length and character set, and copy a string nobody can predict. 👉 Generate one now.

[ Ad Space 728×90 — AdSense ]