How Random Number Generators Work
Learn how random number generators produce values, how seeds and entropy affect randomness, and why secure applications use cryptographically secure random number generators.
Random number generators are algorithms or systems that produce values that appear unpredictable or follow a desired probability distribution. They are used everywhere in software, from simulations and games to randomized testing, sampling, identifiers, and security systems.
Not all random number generators work in the same way. Most software uses pseudo-random number generators, or PRNGs, which produce deterministic sequences from an internal state. Security-sensitive applications instead use cryptographically secure pseudo-random number generators, or CSPRNGs, which are specifically designed to make their output difficult to predict.
What Is a Random Number Generator?
A random number generator is a system that produces values according to some randomness source or algorithm. Depending on the implementation, the generator may produce integers, floating-point numbers, bytes, or values from a particular probability distribution.
Random Number Generator
│
├── Input: seed / entropy / internal state
│
└── Output: random-looking valueA simple generator might produce an integer between two bounds, while a more advanced generator may produce random bytes that are then converted into tokens, identifiers, cryptographic keys, or numbers following a particular distribution.
True Random vs Pseudo-Random Numbers
There are two broad approaches to generating random values: obtaining randomness from a physical process and generating a deterministic sequence using an algorithm.
| Type | Source | Predictability | Typical Use |
|---|---|---|---|
| TRNG | Physical phenomenon | Depends on the physical source | Hardware randomness |
| PRNG | Deterministic algorithm | Predictable if internal state is known | Simulations, games, testing |
| CSPRNG | Algorithm seeded with strong entropy | Designed to resist prediction | Security, tokens, keys |
In practice, modern operating systems can collect environmental entropy and use it to seed or maintain a cryptographically secure generator. Applications can then request secure random bytes without directly interacting with a physical random process.
How a PRNG Works
A pseudo-random number generator uses an algorithm and an internal state to produce a sequence of values. Although the values look random, the sequence is deterministic: if the generator starts from exactly the same state, it produces exactly the same sequence.
Seed
↓
Initial state
↓
PRNG algorithm
↓
Random-looking value
↓
Updated state
↓
Next value
↓
...This deterministic property is not necessarily a weakness. Reproducibility is extremely useful for simulations, automated tests, procedural generation, and debugging.
What Is a Seed?
A seed is an initial value used to establish the starting state of a pseudo-random number generator. The same algorithm combined with the same initial state can reproduce the same sequence.
Seed: 12345
→ 0.4166
→ 0.1018
→ 0.8252
→ 0.2986A seed does not magically make a generator random. It determines where the generator begins in its deterministic sequence. The quality of the resulting sequence depends on the PRNG algorithm and its state.
Why Reproducible Randomness Is Useful
Developers often want the ability to reproduce a sequence of random values. For example, a simulation that produces an unexpected result can be rerun using the same seed to reproduce the exact sequence of events.
- Reproducing simulation results.
- Debugging randomized algorithms.
- Creating deterministic automated tests.
- Generating repeatable procedural content.
- Comparing algorithm performance under identical conditions.
What Is Entropy?
In the context of random generation, entropy represents unpredictability or uncertainty in a source of randomness. A high-quality entropy source provides information that is difficult for an attacker or observer to predict.
Entropy is often discussed in bits. If a value has 128 bits of effective entropy, there are conceptually 2^128 possible equally likely possibilities under the relevant assumptions.
1 bit → 2 possibilities
8 bits → 256 possibilities
32 bits → 4,294,967,296 possibilities
64 bits → 18,446,744,073,709,551,616 possibilities
128 bits → 2^128 possibilitiesThe number of output bits alone does not guarantee that much entropy. If a generator's internal state or seed has low entropy, producing a longer output does not automatically make the output more unpredictable.
How CSPRNGs Work
A cryptographically secure pseudo-random number generator combines a strong internal algorithm with unpredictable initial or refreshed state. Its design aims to prevent an attacker from predicting future output or reconstructing previous output from observations.
Operating system entropy
↓
Secure random state
↓
CSPRNG
↓
Random bytes / values
↓
Tokens, keys, nonces, IDsThe exact construction differs between operating systems and cryptographic libraries. Applications should normally use the operating system's secure random API rather than implementing their own CSPRNG.
PRNG vs CSPRNG
| Property | PRNG | CSPRNG |
|---|---|---|
| Deterministic | Yes | Yes |
| Designed for simulation | Yes | Not primarily |
| Designed for security | No | Yes |
| Reproducible with state/seed | Yes | Potentially, but state must be protected |
| Suitable for passwords | No | Yes |
| Suitable for API secrets | No | Yes |
| Suitable for simulations | Yes | Yes, although often unnecessary |
| Output prediction resistance | Not generally | Designed for it |
The most important distinction is purpose. A fast statistical PRNG can be excellent for simulations while being completely inappropriate for generating authentication tokens.
Why Ordinary Randomness Is Not Secure
Many general-purpose random functions prioritize speed, reproducibility, or statistical quality rather than resistance to attackers. If an attacker can infer the generator's internal state, future outputs may become predictable.
This matters whenever a random value controls access to something valuable. Examples include password reset tokens, session identifiers, API credentials, authentication challenges, and cryptographic keys.
How Random Integers Are Generated
A generator usually produces a stream of random bits and then converts those bits into the requested numeric range. For example, an application may need a value from 0 through 99.
Random bits
↓
Integer representation
↓
Map to requested range
↓
0 ... 99A naive modulo operation can introduce bias when the number of possible source values is not evenly divisible by the size of the requested range. High-quality APIs use techniques such as rejection sampling when uniformity matters.
What Is Modulo Bias?
Modulo bias occurs when a set of equally likely source values is mapped onto a smaller range using modulo and the sizes do not divide evenly.
Suppose the source has 10 values:
0 1 2 3 4 5 6 7 8 9
Mapping with x % 4:
0 → 0
1 → 1
2 → 2
3 → 3
4 → 0
5 → 1
6 → 2
7 → 3
8 → 0
9 → 1
0 and 1 occur more often than 2 and 3.For ordinary non-security applications this may or may not matter depending on the task. For security-sensitive random selection, unbiased generation should be used.
How Random Decimal Numbers Work
Random decimal generators commonly produce a value in an interval such as 0 inclusive through 1 exclusive and then scale it to another range.
Random value in [0, 1)
↓
Multiply by range
↓
Add minimum
↓
Random value in [min, max)Floating-point representation introduces its own limitations. Not every mathematically possible decimal value can be represented exactly by a binary floating-point type.
Uniform Randomness
A uniform random distribution gives every value in the selected discrete set the same probability. For example, a fair six-sided die has a one-in-six probability for each face.
| Value | Probability |
|---|---|
| 1 | 1/6 |
| 2 | 1/6 |
| 3 | 1/6 |
| 4 | 1/6 |
| 5 | 1/6 |
| 6 | 1/6 |
Not every random process is uniform. Applications may deliberately use distributions such as normal, exponential, Poisson, or weighted distributions when modeling real-world phenomena.
Statistical Randomness vs Cryptographic Randomness
A generator can pass statistical tests while still being unsuitable for security. Statistical randomness asks whether output behaves sufficiently like the desired distribution. Cryptographic randomness additionally considers whether an adversary can predict or reconstruct the generator's state.
| Question | Statistical PRNG | CSPRNG |
|---|---|---|
| Do outputs look random? | Important | Important |
| Is the distribution appropriate? | Important | Important |
| Can future output be predicted? | Not necessarily protected | Designed to resist prediction |
| Can internal state be recovered? | May be possible | Designed to make this difficult |
| Suitable for security secrets? | Generally no | Yes |
What Happens If the Seed Is Predictable?
If a PRNG uses a predictable seed, an attacker may be able to reproduce its output. This was historically a common source of security vulnerabilities when programs seeded generators using values such as the current time.
Current time
↓
Predictable seed
↓
Predictable PRNG state
↓
Predictable outputModern security-sensitive applications should obtain seeds from an operating system cryptographic random source rather than constructing them from predictable application data.
Can Random Numbers Be Predicted?
Whether random output can be predicted depends on the generator. A deterministic PRNG is mathematically predictable if its internal state is known. Some poorly designed or incorrectly seeded generators may also allow state recovery from observed outputs.
A properly designed CSPRNG is specifically constructed to make practical prediction infeasible under its security assumptions, even when an attacker can observe some generated values.
How Operating Systems Provide Secure Randomness
Modern operating systems maintain cryptographic random sources that collect environmental information and use it to maintain a secure random state. Applications can request random bytes through operating-system APIs instead of trying to collect physical entropy themselves.
For web applications, browser APIs such as crypto.getRandomValues() provide access to cryptographically strong random values suitable for many security-sensitive client-side tasks.
const bytes = new Uint8Array(16);
crypto.getRandomValues(bytes);
console.log(bytes);Secure Randomness in JavaScript
JavaScript applications should distinguish between Math.random() and cryptographic randomness. Math.random() is intended for general-purpose pseudo-random values and should not be used for security-sensitive secrets.
// General-purpose randomness
const value = Math.random();
// Cryptographically strong random bytes
const bytes = new Uint8Array(16);
crypto.getRandomValues(bytes);The appropriate API can depend on whether the code runs in a browser or server environment. In Node.js, the crypto module provides cryptographic random functions designed for security-sensitive applications.
Randomness and Password Generation
Password generators need a strong source of randomness because an attacker may attempt to guess generated passwords. A secure password generator should use a CSPRNG and select characters without introducing meaningful bias.
The security of a generated password depends on its effective entropy, not simply on the number of characters displayed. A short password selected from a small predictable set can be weak even if it was technically generated by a random function.
Randomness and Tokens
Session tokens, password-reset links, email verification tokens, and API secrets should be generated using cryptographically secure randomness. The token should have enough entropy to make guessing infeasible.
Secure random bytes
↓
Encode as hex / Base64 / Base64url
↓
Opaque token
↓
Use for authentication or authorizationRandomness and UUIDs
Some UUID versions depend heavily on randomness. UUID v4, for example, is primarily randomly generated. The quality of the random source therefore matters when generating UUID v4 values for security-sensitive or collision-sensitive applications.
Other identifier formats use timestamps, counters, or additional structured components. The correct generator depends on whether the application needs randomness, ordering, interoperability, compactness, or other properties.
Random Number Generator Period
The period of a PRNG is the length of its sequence before the internal state repeats. A generator with a larger state can have an extremely long period, allowing it to produce a huge number of values before repeating.
A long period alone does not prove that a PRNG is suitable for security or that its output distribution is ideal. Period, statistical quality, state size, predictability resistance, and implementation quality are separate properties.
Randomness Tests
Random generators can be evaluated using statistical tests that look for patterns or deviations from expected distributions. Test suites may examine properties such as frequency, runs, correlations, and other characteristics.
Passing statistical tests does not prove that a generator is cryptographically secure. A generator may have excellent statistical properties while still allowing an attacker to predict future output after observing enough values.
Common Random Number Generator Algorithms
| Algorithm / Family | Typical Characteristic | Typical Use |
|---|---|---|
| Linear Congruential Generator | Simple and fast | Legacy simulations and teaching |
| Mersenne Twister | Very long period | Simulation and general-purpose randomness |
| PCG family | Good statistical properties and small state variants | General-purpose PRNG |
| Xorshift family | Very fast and simple | Performance-sensitive non-security tasks |
| CSPRNGs | Designed for unpredictability | Security-sensitive applications |
The best choice depends on the application. A generator designed for simulations is not automatically appropriate for authentication or cryptography.
Why Randomness Is Important in Simulations
Simulations often need large quantities of random-looking values while remaining reproducible. A seeded PRNG is ideal for many such workloads because the simulation can be rerun using the same initial state.
- Monte Carlo simulations.
- Game mechanics.
- Procedural world generation.
- Statistical experiments.
- Load and stress testing.
- Machine learning experiments.
Randomness in Games
Games frequently use pseudo-random generation for events such as loot drops, enemy behavior, map generation, critical hits, and procedural content. Reproducible seeds can be useful when developers want the same world or scenario to be generated repeatedly.
Game randomness does not usually need cryptographic security unless the random values affect a security-sensitive or competitive mechanism where predictability could be exploited.
Random Number Generation in APIs
An API that returns random values should clearly define the range, distribution, precision, and whether the values are cryptographically secure. Calling something 'random' without specifying these properties can be misleading.
| Requirement | Important Detail |
|---|---|
| Integer range | Define minimum and maximum behavior |
| Decimal range | Define interval and precision |
| Distribution | Uniform or another specified distribution |
| Security | Use CSPRNG when values are sensitive |
| Reproducibility | Use a controlled seed when required |
Common Randomness Mistakes
- Using Math.random() for security-sensitive values.
- Using the current time as the only seed for a security token.
- Assuming more output digits automatically mean more entropy.
- Using modulo without considering bias.
- Confusing statistical randomness with cryptographic unpredictability.
- Assuming a long PRNG period makes it secure.
- Creating a custom random algorithm instead of using a trusted implementation.
- Using predictable random values for password reset or session tokens.
- Ignoring the required probability distribution.
Random Number Generator Best Practices
- Use a well-tested PRNG for simulations and reproducible non-security workloads.
- Use a CSPRNG for passwords, tokens, keys, and other security-sensitive values.
- Obtain cryptographic seeds from trusted operating-system sources.
- Avoid implementing cryptographic random generation yourself.
- Use unbiased range-selection algorithms when uniformity matters.
- Define the distribution and numeric range explicitly.
- Use explicit seeds when reproducibility is required.
- Do not treat random-looking output as proof of security.
Random Number Generator vs Random Decimal Generator
A Random Number Generator usually focuses on producing integer values within a selected range, while a Random Decimal Generator produces floating-point values. Both can be implemented using the same underlying random source but use different conversion and range logic.
Secure Random Generator vs Regular Random Generator
A regular random generator is usually optimized for speed, convenience, reproducibility, or statistical properties. A secure random generator is designed specifically to resist prediction and state-recovery attacks.
| Use Case | Recommended Generator |
|---|---|
| Random UI effects | Regular PRNG |
| Simulation | High-quality PRNG |
| Procedural generation | Seeded PRNG |
| Automated tests | Seeded PRNG |
| Password generation | CSPRNG |
| Session IDs | CSPRNG |
| API secrets | CSPRNG |
| Cryptographic keys | CSPRNG / cryptographic API |
Frequently Asked Questions
How does a random number generator work?
A random number generator produces values from a source of randomness and maps them into a desired range or distribution. Software commonly uses deterministic pseudo-random algorithms or cryptographically secure random generators.
What is a PRNG?
A pseudo-random number generator (PRNG) is a deterministic algorithm that produces a sequence of random-looking values from an internal state. Given the same initial state and algorithm, the sequence can generally be reproduced.
What is a CSPRNG?
A cryptographically secure pseudo-random number generator (CSPRNG) is designed to produce output that is difficult to predict or reconstruct, making it suitable for security-sensitive values such as tokens, keys, and passwords.
What is a random seed?
A seed initializes the internal state of a PRNG. With the same algorithm and compatible implementation, using the same seed can reproduce the same sequence of values.
Is Math.random() secure?
No. Math.random() is intended for general-purpose pseudo-randomness and should not be used to generate passwords, authentication tokens, cryptographic keys, or other security-sensitive values.
What is entropy in random number generation?
Entropy describes the amount of unpredictability available in a randomness source. It is commonly expressed in bits, with more entropy generally meaning a larger number of unpredictable possible states.
What is modulo bias?
Modulo bias occurs when a uniformly distributed random source cannot be divided evenly into the desired range. Simple modulo operations can then make some results more likely than others.
What random number generator should I use for passwords?
Use a cryptographically secure random generator provided by the operating system, browser, or a trusted cryptographic library. General-purpose PRNGs should not be used for passwords or other security-sensitive values.
Useful Randomness Tools
The Random Number Generator can produce integer values within a selected range, while the Random Decimal Generator is useful for floating-point values. The Secure Random Generator is intended for cryptographically strong random values, and the Random Seed Generator can create seeds for reproducible workflows. The Entropy Calculator can help estimate the number of bits represented by a set of possible values.
Conclusion
Random number generation is not a single technique. Most software randomness comes from deterministic pseudo-random algorithms, while security-sensitive applications rely on cryptographically secure generators backed by strong entropy sources.
The key distinction is between randomness that is statistically useful and randomness that is unpredictable to an attacker. PRNGs are excellent for simulations, games and reproducible tests, while CSPRNGs should be used for passwords, tokens, keys and other security-sensitive values.
Understanding seeds, entropy, distributions, internal state and range-selection methods makes it easier to choose the right random generator for each task and avoid common mistakes such as predictable seeds, modulo bias and insecure use of general-purpose random functions.