How Random Number Generators Work (and Can You Beat Them?)

How Do Random Number Generators Actually Work?

The direct answer to “how do random number generators actually work?” is this: they either compute a deterministic sequence from a secret starting value (a seed) using a mathematical algorithm, or they measure unpredictable physical phenomena to produce raw entropy. Software alone cannot create true randomness; it can only stretch a small amount of real entropy into a longer stream. The security of that stream depends entirely on where the seed came from and whether the algorithm resists prediction.

When I built my first multiplayer game shuffle in 2013, I used Python’s random module (Mersenne Twister) with a fixed seed for “reproducibility.” Within a week a player reverse‑engineered the daily card order because the seed was hardcoded in the client. That early mistake cemented my rule: never confuse reproducibility with security.

Deterministic PRNGs: Seeds and State Machines

A pseudo‑random number generator (PRNG) is a finite state machine. You feed it a seed, it initializes a state vector, and each call runs a transition function that outputs a number and updates the state. Classic linear congruential generators (LCGs) follow Xₙ₊₁ = (aXₙ + c) mod m. Modern generators like PCG64 or xorshift128+ use bit‑mixing to remove patterns.

The thing nobody tells you about LCGs: their low‑order bits are catastrophically non‑random. I’ve debugged simulation code where rand() % 1000 produced a visible sine‑wave bias because the modulus aliased the multiplier. Even the Mersenne Twister, with its 2¹⁹⁹³⁷−1 period, can have its entire 19937‑bit state reconstructed from just 624 consecutive 32‑bit outputs.

True Random Number Generators: Harvesting Physical Entropy

A true random number generator (TRNG) samples chaotic physics: thermal noise across a resistor, shot noise in a diode, or even radioactive decay. Intel’s RDRAND instruction draws from a built‑in thermal noise circuit conditioned by AES‑CBC‑MAC. According to the NIST Random Number Generation project, such sources must pass continuous health tests to detect entropy loss.

In a 2018 industrial IoT deployment, we used an external TRNG chip. At 70°C ambient, the entropy throughput dropped 30% and the vendor’s library silently returned zeros. Most people don’t realize physical entropy degrades with temperature, voltage, and aging—monitoring is not optional.

CSPRNGs: The Cryptographic Middle Ground

A cryptographically secure PRNG (CSPRNG) adds two guarantees: next‑bit unpredictability and resistance to state recovery even after observing many outputs. NIST SP 800‑90A defines CTR_DRBG (AES‑CTR based) and HMAC_DRBG. The NIST SP 800‑90A revision 1 removed the suspicious Dual_EC_DRBG and specifies exact reseeding rules.

I migrated a token‑issuing service to HMAC_DRBG after a pentest showed our old PRNG leaked correlations. The trade‑off: CSPRNGs cost 5–50× more CPU per byte than MT19937. For a login token that’s irrelevant; for a Monte Carlo sim with 10¹² draws, it’s a real bill.

Can You Beat a Random Number Generator?

Yes—if the generator uses a weak seed, a non‑cryptographic algorithm, or a broken entropy source. No—if it is a properly seeded CSPRNG with ≥128 bits of entropy and continuous reseeding. The practical attacker asks: “Do I know the internal state or can I guess the seed?” not “Is the algorithm secret?”

The Predictability Spectrum

At the weak end, a PRNG seeded with time(NULL) (seconds since 1970) yields ~2³² possible seeds if the year is known. A GPU can brute‑force that in under a minute. At the strong end, a CSPRNG keyed with 256 bits of entropy requires 2¹²⁸ operations to beat—beyond any realistic compute.

In a 2020 audit of a mobile betting app, I found its “random” shuffle used Java’s java.util.Random seeded by System.currentTimeMillis(). We captured one public hand and solved for the seed in 40 ms using a local solver. That is beating the RNG with trivial effort.

Attack Models: State Recovery and Seed Guessing

State recovery attacks exploit the fact that PRNGs are deterministic. If an attacker observes enough output (624 words for MT19937) they invert the transformation. Seed guessing attacks target low‑entropy seeds via dictionary or brute force. Both are defeated only by cryptographic mixing and high‑entropy seeds.

One engagement involved a custom RNG that XORed the output of sin(seed + i). It passed a histogram test but the seed space was 2²⁴ because the developer used a 24‑bit timer. We enumerated it in 3 seconds. Statistical pass ≠ unpredictable.

Real‑World Exploits: When RNGs Failed

History is full of beatable RNGs. Netscape’s 1995 SSL seeded with process ID and clock, letting attackers predict session keys. In 2013, Android’s SecureRandom bug collapsed entropy to zero after a fork, enabling Bitcoin theft. The CERT advisory VU#672991 documents the exact failure.

Casino slots have been beaten too. A 2014 case involved a known PRNG in old Aristocrat machines; attackers recorded reel outcomes, solved for the seed, and timed button presses. The math was fine; the seed loaded from a predictable real‑time clock was the flaw.

Seed Predictability: The Weakest Link

A PRNG is a lock with a combination. If you write the combination on the casing, the lock is useless. Seeds are that combination, and they are where most systems fail.

Common Seeding Mistakes I’ve Audited

  • Using time(NULL) or gettimeofday() alone—at most microsecond precision, ~2⁴⁰ guesses in a known window.
  • Deriving seed from PID, MAC, or build number—static or low‑entropy.
  • Shipping a fixed “reproducible” seed in production (my 2013 game error).
  • Seeding a CSPRNG from another PRNG’s output, creating a circular trust.

In a 2019 financial backtest, a colleague seeded NumPy’s np.random with a constant for repeatable reports, then reused it in a live trading sim. An intern reconstructed the “random” trade sequence in an afternoon because the seed was in the public config repo.

Virtual Machine Snapshots and Cloned Images

Cloud images often ship with a saved entropy pool or a fixed seed file. If you clone a VM without regenerating /var/lib/systemd/random-seed, every clone starts with identical CSPRNG state. I’ve seen a 500‑node Kubernetes fleet generate the same “unique” UUIDs for 10 minutes post‑boot because the base image had a stale seed.

The fix is to call getrandom() after boot and immediately reseed from a fresh hardware source, then delete the seed file. Most orchestration templates omit this step.

Historical Breaches: Theory Meets Vulnerability

Beyond the cases above, the 2008 Debian OpenSSL bug is the textbook example. A maintainer commented out a line, reducing the PRNG’s entropy to the process ID (≤32,768 values). Millions of SSH and TLS keys became predictable. The lesson: RNG code is small, dense, and catastrophic when altered.

The Dual_EC_DRBG controversy showed that even standards can hide predictability. That generator used elliptic‑curve points; knowing a specific secret relationship allowed backdoor prediction. Although rarely deployed, its presence in a NIST draft eroded trust for years. The current SP 800‑90A rev 1 excised it completely.

What Most Post‑Mortems Miss

Most people don’t realize that many breaches weren’t algorithm flaws but operational ones: failing to reseed after fork, logging seeds to debug files, or using a fast PRNG for session cookies. The algorithm was fine; the context was not.

A Practitioner’s RNG Selection Framework

Choosing an RNG is a threat‑model decision, not a popularity contest. I use the matrix below in every architecture review.

Decision Matrix: PRNG vs CSPRNG vs TRNG

Use Case Recommended Generator Why Avoid
Monte Carlo, game visuals PCG64, MT19937 Fast, good distribution Crypto overhead
Session tokens, salts, UUIDs OS CSPRNG (/dev/urandom, Crypto.getRandomValues) Unpredictability LCG, MT19937
Key generation, lottery CSPRNG + hardware TRNG (FIPS 140‑2) Legal & security Clock‑seeded PRNG
Reproducible science PRNG with stored seed Exact replay TRNG (non‑replayable)
HSM, missile guidance Certified TRNG Audited entropy Software‑only

Step‑by‑Step: How to Seed a CSPRNG Correctly

  1. At boot, read at least 32 bytes from the OS entropy source (getrandom on Linux, BCryptGenRandom on Windows).
  2. Instantiate the CSPRNG (e.g., HMAC_DRBG) with those bytes as the personalization string.
  3. Reseed after any process fork, VM resume, or every 2¹⁶ requests (per NIST).
  4. Never log the seed or intermediate state outside a sealed HSM.
  5. Fail closed: if entropy read returns fewer than 16 bytes, halt the service.

For quick non‑production mock data, we sometimes use the Random Number Generator tool to verify distributions, but it is explicitly not for tokens or keys.

The Secure Implementation Checklist

  • Use platform CSPRNG for all security calls; don’t roll your own.
  • Monitor entropy pool size; alert below 256 bits for >60s.
  • Add NIST SP 800‑90B health tests for hardware TRNGs.
  • Rotate seeds on snapshot restore to avoid duplicate sequences.
  • Pen‑test by attempting seed recovery from captured outputs.

Testing Randomness Beyond the Dieharder Suite

Most articles stop at “run Dieharder.” That catches only coarse failures. I’ve seen a custom PRNG pass Dieharder yet be fully predictable because its seed was 16 bits. Statistical tests measure distribution, not secrecy.

TestU01 and PractRand: Beyond NIST STS

For deep evaluation I use TestU01 (Rabbit, SmallCrush, Crush) and PractRand, which detect subtle correlations in terabyte streams. A 2021 side project compared three PRNGs: MT19937 passed all, but a naive xorshift failed PractRand at 1 GB. Still, none of those tests would flag a weak seed—only an attacker model does.

Runtime Entropy Monitoring

In production, I export /proc/sys/kernel/random/entropy_avail to Prometheus and alert on drops. On embedded Linux, a watchdog reboots the device if the TRNG health test fails twice. This saved a payment terminal fleet from silent key duplication after a capacitor fault.

Final Takeaways: What I Tell Every Developer

If you remember one thing: a random number generator is only as strong as its seed and its threat model. Use a CSPRNG for anything security‑related, verify entropy at boot, and never trust a “random” function you haven’t traced to its origin.

The moment you ship a predictable seed to production, you haven’t built a random generator—you’ve built a predictable one with extra steps.

For non‑critical experiments, the Random Number Generator on our site is handy, but keep cryptographic needs on vetted system APIs and audited hardware.

Leave a Reply

Your email address will not be published. Required fields are marked *