Random Number Generators Explained: PRNG vs TRNG and How They Work
Understand how random number generators work, the difference between true random (TRNG) and pseudo-random (PRNG), entropy sources, and real-world applications from cryptography to Monte Carlo simulations.
Introduction
Random numbers are everywhere in modern life, even if you never think about them. Every time you shuffle a playlist, draw lottery numbers, encrypt a message, run a scientific simulation, or see a CAPTCHA, random number generators are working behind the scenes. The global cybersecurity industry depends on randomness for encryption keys that protect trillions of dollars in transactions every day.
But here is the paradox: computers are deterministic machines. They execute instructions in a precise, repeatable sequence. So how does a deterministic machine produce something unpredictable?
The answer involves a fascinating mix of mathematics, physics, and engineering. There are generators that harvest randomness from the physical world, generators that use clever algorithms to produce sequences that look random, and hybrid generators that combine both approaches for cryptographic security.
This guide explains how random number generators work, the critical differences between true random and pseudo-random generation, where the entropy that seeds randomness comes from, real-world applications, notable failures that exposed weaknesses in random number systems, and practical programming examples.
Try our free Random Number Generator to generate random numbers instantly with custom ranges, quantities, and no-repeat options.
What Is a Random Number Generator?
A random number generator (RNG) is any process or device that produces a sequence of numbers with no discernible pattern. In an ideal RNG, each number in the output is statistically independent of all others, and every possible value within the range has an equal probability of being selected.
In practice, there is a spectrum of "randomness quality" depending on the method used:
- True Random Number Generators (TRNGs) produce genuinely unpredictable numbers derived from physical phenomena
- Pseudo-Random Number Generators (PRNGs) produce deterministic sequences that appear random but are entirely reproducible given the same starting conditions
- Cryptographically Secure PRNGs (CSPRNGs) are a subset of PRNGs designed to be computationally infeasible to predict, even if an attacker knows the algorithm
Understanding which type to use depends entirely on the application. A video game needs fast, good-enough randomness. An encryption system needs computationally unpredictable randomness. A physics simulation might need reproducible randomness for verification.
True Random Number Generators (TRNGs)
True random number generators derive their output from physical phenomena that are fundamentally unpredictable. These are also called hardware random number generators.
Common Entropy Sources
Thermal noise: Electronic components generate tiny voltage fluctuations due to the random motion of electrons at any temperature above absolute zero. These fluctuations are genuinely random at the quantum level and can be amplified and digitized.
Atmospheric noise: Radio receivers tuned between stations pick up atmospheric electromagnetic noise from lightning strikes and other natural phenomena. The service random.org uses atmospheric noise to generate random numbers.
Radioactive decay: The timing of radioactive decay events is governed by quantum mechanics and is fundamentally unpredictable. Geiger counter clicks can be converted to random bits.
Photon behavior: When a single photon hits a beam splitter, quantum mechanics says it has a 50/50 chance of being transmitted or reflected. This produces truly random bits at high speed.
Clock jitter: The slight variations in CPU clock timing, caused by thermal effects and electrical noise, provide a source of entropy available in any computer.
Advantages and Limitations
Advantages:
- Produces genuinely unpredictable output
- Cannot be reproduced or predicted, even in principle
- Suitable for the highest security applications
Limitations:
- Generally slower than algorithmic methods
- Requires specialized hardware
- Output rate is limited by the physical process
- Raw output may have slight biases that need post-processing
Pseudo-Random Number Generators (PRNGs)
Pseudo-random number generators use deterministic mathematical algorithms to produce sequences of numbers that pass statistical tests for randomness. Despite being entirely predictable from their initial state, well-designed PRNGs produce output that is practically indistinguishable from true randomness for most applications.
How PRNGs Work
Every PRNG follows the same basic pattern:
- Seed: An initial value (the seed) sets the generator's internal state
- Algorithm: A mathematical function transforms the current state into the next state and produces an output number
- Repeat: The process continues, with each state producing the next
The same seed always produces the same sequence. This is actually useful for reproducibility in simulations and testing.
Common PRNG Algorithms
Linear Congruential Generator (LCG): One of the oldest and simplest PRNGs. Uses the formula: next = (a * current + c) mod m. Fast but has known weaknesses including short periods and predictable patterns in lower bits. The C standard library's rand() traditionally uses an LCG.
Mersenne Twister (MT19937): The most widely used general-purpose PRNG. It has a period of 2^19937 - 1 (a number with 6,002 digits), passes most statistical tests, and is the default PRNG in Python, Ruby, R, MATLAB, and many other languages. However, it is not cryptographically secure — observing 624 consecutive outputs allows complete prediction of all future outputs.
Xorshift family (xoshiro, xoroshiro): Modern, fast PRNGs that use bitwise XOR and shift operations. They offer excellent statistical quality with very high speed, making them popular for games and simulations. Developed by Sebastiano Vigna and David Blackman.
PCG (Permuted Congruential Generator): A family of PRNGs designed by Melissa O'Neill that combines an LCG with a permutation function. PCG generators are fast, have good statistical properties, and are relatively small in state size.
When PRNGs Are Sufficient
PRNGs are appropriate when you need:
- Speed (millions or billions of numbers per second)
- Reproducibility (same seed = same sequence)
- Statistical quality without cryptographic security
- Simulation, gaming, Monte Carlo methods, or statistical sampling
Cryptographically Secure PRNGs (CSPRNGs)
A CSPRNG bridges the gap between true randomness and algorithmic speed. It is a PRNG with additional security guarantees that make it suitable for cryptographic applications.
Security Requirements
A CSPRNG must satisfy two properties:
-
Next-bit test: Given the first k bits of a random sequence, there is no polynomial-time algorithm that can predict bit k+1 with probability significantly greater than 50%.
-
State compromise extension resistance: Even if an attacker learns the generator's current internal state, they cannot determine previous outputs (backward security).
How CSPRNGs Get Entropy
CSPRNGs are seeded with true randomness gathered from multiple hardware sources:
- Keyboard and mouse timing: Microsecond-level variations in user input timing
- Disk I/O timing: Variations in hard drive seek times and SSD access patterns
- Network packet arrival times: Timing jitter in network traffic
- CPU instruction timing: Variations from cache effects and branch prediction
- Hardware RNG instructions: Modern CPUs (Intel RDRAND, AMD) include dedicated hardware entropy sources
- Interrupt timing: Variations in when hardware interrupts occur
The operating system collects this entropy into an "entropy pool" that feeds the CSPRNG. On Linux, this is /dev/urandom. On Windows, it is CryptGenRandom. In browsers, the Web Crypto API's crypto.getRandomValues() accesses the OS entropy pool.
Common CSPRNGs
AES-CTR DRBG: Uses the AES block cipher in counter mode as a PRNG. This is the NIST-recommended default and is widely deployed.
ChaCha20: A stream cipher by Daniel J. Bernstein, used as a CSPRNG in Linux (since kernel 4.8), FreeBSD, and many applications. It is fast in software and resistant to timing side-channel attacks.
Fortuna: Designed by Bruce Schneier and Niels Ferguson, Fortuna uses multiple entropy pools and automatically reseeds from system entropy. It is used in macOS and iOS.
How Computers Generate Random Numbers
Let us trace the full path from physical entropy to the random number you see on screen.
The Entropy Pipeline
- Hardware events generate raw entropy (key presses, mouse movements, disk timing, thermal noise from the CPU's hardware RNG)
- The OS entropy pool collects and mixes entropy from multiple sources, maintaining an estimate of available randomness
- The CSPRNG is seeded from the entropy pool and uses a cryptographic algorithm to stretch a small amount of true randomness into a large stream of cryptographically secure pseudo-random bits
- The application calls the system's random API to get numbers in the desired format and range
Seed Values
A seed is the initial state that starts a PRNG. The quality of the seed directly determines the quality of the output:
- Bad seed: Using the current time as a seed (common in older systems) means anyone who knows approximately when the generator was started can narrow down the seed space dramatically
- Good seed: A 256-bit value from a CSPRNG provides 2^256 possible starting states — more than the number of atoms in the observable universe
- Reproducible seed: In scientific computing, deliberately choosing a fixed seed allows experiments to be reproduced exactly, which is valuable for debugging and verification
Uniform Distribution
Most RNGs produce uniformly distributed integers — each value in the range has equal probability. Converting to other distributions requires additional math:
- Normal (Gaussian) distribution: The Box-Muller transform converts two uniform random numbers into two normally distributed numbers
- Exponential distribution: Apply the inverse CDF:
-ln(1 - U) / lambdawhere U is uniform [0,1) - Custom distributions: Use the inverse transform method or rejection sampling
Applications of Random Numbers
Gaming
Video games use random numbers extensively: loot drop rates, critical hit chances, procedural world generation, AI decision-making, card shuffling, dice rolling, and spawn point selection. Most games use fast PRNGs like xoshiro256** because speed matters more than cryptographic security.
Cryptography
Randomness is the foundation of modern cryptography. Random numbers are needed for:
- Encryption keys: AES-256 requires a truly random 256-bit key
- Initialization vectors (IVs): Prevent identical plaintexts from producing identical ciphertexts
- Nonces: One-time values used in authentication protocols
- Salt values: Random data added to passwords before hashing
- Session tokens: Unpredictable identifiers for web sessions
Any weakness in the random number generator used for cryptography can compromise the entire security system.
Statistics and Science
- Monte Carlo simulations: Estimate complex mathematical quantities by random sampling (used in physics, finance, engineering)
- Bootstrap resampling: Statistical technique that resamples data with replacement to estimate confidence intervals
- Randomized controlled trials: Randomly assigning participants to treatment and control groups
- Stochastic modeling: Weather prediction, epidemiology, and financial markets all use random number generation
Lottery and Gaming Compliance
Legal lottery systems require certified RNGs that meet strict standards. Most jurisdictions require either hardware TRNGs or thoroughly tested and audited CSPRNGs. Testing typically involves running the generator through statistical test suites (NIST SP 800-22, Dieharder, TestU01) that verify the output shows no detectable patterns.
Famous Randomness Failures
History shows that getting randomness wrong can have severe consequences.
Dual_EC_DRBG: The NSA Backdoor
In 2006, NIST standardized Dual_EC_DRBG (Dual Elliptic Curve Deterministic Random Bit Generator) as an approved CSPRNG. Cryptographers quickly noticed it was suspiciously slow and had unexplained constants that could function as a backdoor. In 2013, Edward Snowden's documents confirmed the NSA had deliberately inserted a backdoor, allowing them to predict the output of any system using the default constants. RSA Security had used it as the default in their BSAFE toolkit, and NIST withdrew the standard in 2014.
Lesson: Transparency in algorithm design matters. Constants should have verifiable, nothing-up-my-sleeve origins.
PHP's rand() and mt_rand()
PHP's rand() function historically used a weak LCG with a small state, making it trivially predictable. The replacement mt_rand() (Mersenne Twister) improved statistical quality but remained non-cryptographic. Attackers exploited mt_rand() in web applications to predict session tokens, CSRF tokens, and password reset links. After observing enough outputs, the internal state could be fully recovered.
Lesson: Never use general-purpose PRNGs for security-sensitive applications. Use random_int() or random_bytes() in PHP, which use the OS CSPRNG.
The Debian OpenSSL Bug (2008)
In 2006, a Debian maintainer commented out two lines of code in OpenSSL's random number generator that a code analysis tool flagged as using uninitialized memory. Those lines were actually the primary entropy source. For two years, every SSL key, SSH key, and other cryptographic key generated on Debian and Ubuntu systems had at most 32,768 possible values instead of the intended astronomical number. Any key generated during this period could be guessed in seconds.
Lesson: Changes to cryptographic code require expert review. Automated tools can flag legitimate behavior as bugs.
The PlayStation 3 ECDSA Hack (2010)
Sony's PlayStation 3 code signing used ECDSA (Elliptic Curve Digital Signature Algorithm), which requires a fresh random nonce for each signature. Sony used the same nonce for every signature. This mathematical error allowed hackers to recover Sony's private signing key, enabling the installation of unauthorized software on any PS3.
Lesson: Reusing random values in cryptographic protocols can be catastrophic. Nonces must be unique.
The RANDU Disaster (1960s)
IBM's RANDU generator, used widely in scientific computing throughout the 1960s and 1970s, had a severe flaw: when plotted in three dimensions, its output fell on just 15 parallel planes instead of filling the space uniformly. Countless scientific simulations and research papers published during this era used RANDU, and their results may have been compromised by this non-randomness. The generator was so widely distributed that some affected studies were never identified or corrected.
Lesson: Statistical testing of random number generators is essential. Visual inspection (plotting in multiple dimensions) can reveal patterns that simple one-dimensional tests miss.
Random Number Generation in Programming
JavaScript
Python
Key Differences Between Languages
| Feature | JavaScript | Python |
|---|---|---|
| Basic PRNG | Math.random() | random.random() |
| Integer range | Math.floor(Math.random() * n) | random.randint(a, b) |
| Crypto-secure | crypto.getRandomValues() | secrets.token_bytes() |
| Seedable | No (Math.random) | Yes (random.seed()) |
| No-repeat sampling | Manual Fisher-Yates | random.sample() |
Probability and Fairness
Uniform Distribution
A fair random number generator produces a uniform distribution: every possible value has exactly the same probability of being selected. For a range of 1-100, each number should appear approximately 1% of the time over many draws.
Testing Randomness
How do you verify that a generator is actually producing good random numbers? Several standard test suites exist:
NIST SP 800-22: The US National Institute of Standards and Technology's test suite includes 15 statistical tests: frequency test, runs test, longest run test, FFT test, serial test, and others. Used for certifying CSPRNGs.
Dieharder: A comprehensive suite of 31+ statistical tests developed by Robert G. Brown at Duke University. Tests include birthday spacings, overlapping permutations, parking lot test, and squeeze test.
TestU01: Developed by Pierre L'Ecuyer at the University of Montreal, TestU01 includes the "Big Crush" battery of 160 statistical tests. It is considered the most stringent general-purpose test suite for PRNGs.
The Birthday Paradox and Collisions
When generating random numbers, collisions (repeated values) occur sooner than most people expect. In a group of just 23 people, there is a 50% chance that two share a birthday (out of 365 possible days). Similarly:
- Generating random 32-bit integers, you can expect a collision after about 77,000 numbers
- For 64-bit integers, collisions appear after about 5 billion numbers
- For 128-bit values, collisions appear after about 2^64 (18 quintillion) values
This matters for generating unique identifiers. UUIDs (128-bit) are large enough that collisions are practically impossible, but shorter random IDs may collide sooner than expected.
Bias in Random Number Generation
A subtle issue arises when mapping a PRNG's output to a specific range. If the PRNG produces values 0-255 and you want numbers 1-100, using value % 100 + 1 introduces a slight bias: values 1-56 are slightly more likely than 57-100 because 256 is not evenly divisible by 100. The correct approach is rejection sampling: discard values that would cause bias and regenerate.
Frequently Asked Questions
Is Math.random() in JavaScript safe for passwords?
No. Math.random() is a fast PRNG (typically xorshift128+ in modern engines) that is not cryptographically secure. Its internal state can be recovered from observed outputs. For passwords, tokens, or any security purpose, use crypto.getRandomValues() or the Web Crypto API.
How do slot machines generate random outcomes?
Modern slot machines use certified CSPRNGs that continuously generate random numbers (typically thousands per second), even when no one is playing. The exact moment a player presses the spin button determines which random number is used, which maps to a specific reel configuration. Gaming commissions test and certify these RNGs to ensure fairness.
Can a quantum computer break random number generators?
Quantum computers cannot break TRNGs because true randomness from physical phenomena remains unpredictable regardless of computing power. However, quantum computers could theoretically break certain CSPRNGs if the underlying cryptographic primitives (like AES or elliptic curves) become vulnerable. Post-quantum CSPRNG designs are being developed to address this.
What is the difference between Math.random() and crypto.getRandomValues()?
Math.random() returns a floating-point number between 0 and 1 using a fast but non-secure algorithm. It is suitable for games and simulations. crypto.getRandomValues() fills a typed array with cryptographically strong random values sourced from the operating system's entropy pool. It is suitable for security-sensitive applications but slightly slower.
How do you generate a random number with a normal (bell curve) distribution?
Use the Box-Muller transform: generate two uniform random numbers U1 and U2 between 0 and 1, then compute Z = sqrt(-2 * ln(U1)) * cos(2 * pi * U2). Z will follow a standard normal distribution (mean 0, standard deviation 1). Scale and shift as needed: result = mean + Z * standardDeviation.
Why should you never use the current time as a random seed for security?
The current time is predictable. An attacker who knows approximately when a key was generated can try all possible timestamps in that window. Even with millisecond precision, there are only about 86,400,000 possible seeds per day — trivially searchable by a modern computer. Security-sensitive applications must use entropy from hardware sources via the OS CSPRNG.
How do you test if a random number generator is fair?
Run the generator many times (at least 10,000 iterations) and check that the distribution of results matches the expected distribution. For a uniform generator producing values 1-6, each value should appear approximately 1/6 of the time. Apply chi-squared tests to verify statistical uniformity. For more rigorous testing, use standardized test suites like NIST SP 800-22 or TestU01's Big Crush, which apply dozens of statistical tests covering frequency analysis, serial correlation, longest runs, spectral analysis, and more.