Ctrl + K
Random14 min read

Pseudorandom vs Cryptographically Secure Random

Understand how pseudorandom generators differ from cryptographically secure random generators and when to use each type.

Published: 2026-09-02

Pseudorandom and cryptographically secure random generators both produce values that appear random, but they are designed for different purposes. A pseudorandom number generator, or PRNG, focuses on producing a useful sequence of values efficiently. A cryptographically secure pseudorandom number generator, or CSPRNG, adds a much stronger requirement: an attacker should not be able to practically predict its output.

This distinction is critical in software development. A normal PRNG can be perfectly suitable for simulations, games, randomized testing, and procedural generation while being completely inappropriate for passwords, API keys, session tokens, reset links, or cryptographic keys.

Pseudorandom vs Cryptographically Secure Random at a Glance

PropertyPRNGCSPRNG
Primary purposeFast statistical randomnessSecurity and unpredictability
DeterministicYesYes internally
Seed/state mattersYesYes
Designed to resist predictionNoYes
Suitable for simulationsYesYes
Suitable for gamesYesYes
Suitable for passwordsNoYes
Suitable for API keysNoYes
Suitable for session tokensNoYes
Typical performanceVery fastUsually fast enough for application security

What Is a Pseudorandom Number Generator?

A pseudorandom number generator is an algorithm that produces a deterministic sequence of values that has statistical characteristics resembling randomness. The generator maintains an internal state and updates that state each time it produces output.

Seed
  ↓
Initial state
  ↓
PRNG algorithm
  ↓
Output #1
  ↓
Updated state
  ↓
Output #2
  ↓
Updated state
  ↓
Output #3

The word 'pseudo' is important. The sequence is not truly nondeterministic. If someone knows the exact algorithm and the complete internal state, they can calculate the sequence.

Why PRNGs Are Still Useful

Predictability is not always a problem. In many applications, reproducibility is actually an advantage. Developers may intentionally initialize a PRNG with a known seed so that the same sequence can be generated again later.

  • Monte Carlo simulations.
  • Procedural content generation.
  • Game mechanics.
  • Randomized algorithms.
  • Automated tests.
  • Statistical experiments.
  • Performance benchmarking.

For example, if a simulation produces a rare bug after millions of random events, a developer can record the seed and reproduce the same sequence to investigate the problem.

What Is a CSPRNG?

A cryptographically secure pseudorandom number generator is a generator designed to satisfy security properties that ordinary PRNGs do not necessarily provide. Its output should be computationally infeasible to predict, even when an attacker knows the algorithm and can observe some generated values.

Strong entropy
     ↓
Secure internal state
     ↓
CSPRNG
     ↓
Unpredictable random bytes
     ↓
Tokens / keys / secrets

CSPRNGs are normally seeded and maintained using operating-system or hardware-backed sources of entropy. Application developers should generally rely on trusted cryptographic APIs instead of implementing their own secure random algorithm.

The Most Important Difference: Predictability

The central difference between a conventional PRNG and a CSPRNG is resistance to prediction. A conventional PRNG may be statistically excellent while still allowing an attacker to reconstruct its state after observing enough output.

A CSPRNG is specifically designed to make this type of attack impractical. Its security depends on the quality of its design, implementation, entropy source, and protection of its internal state.

How Seeds Affect Randomness

A seed initializes a pseudorandom generator. With a conventional PRNG, knowing the seed can be enough to reproduce the complete sequence.

Same algorithm
      +
Same seed
      =
Same sequence

This property is useful for simulations but dangerous for security-sensitive generation. If a secret token is generated from a predictable seed, an attacker may be able to reconstruct the token.

Why Time-Based Seeds Can Be Dangerous

A common historical mistake was to seed a PRNG with the current time. Time is often predictable within a relatively small range. If an attacker knows approximately when a token was generated, they may only need to test a limited number of possible seeds.

Current timestamp
       ↓
Predictable seed
       ↓
Predictable PRNG state
       ↓
Predictable token
⚠️ Do not use timestamps, user IDs, counters, or other predictable application values as the sole source of randomness for security-sensitive secrets.

Entropy and Security

Entropy describes the amount of unpredictability available to a random process. In security contexts, effective entropy is more important than simply counting output characters or digits.

Nominal SizePossible Values
8 bits2^8 = 256
16 bits2^16 = 65,536
32 bits2^32 ≈ 4.3 billion
64 bits2^64 ≈ 18.4 quintillion
128 bits2^128
256 bits2^256

A 128-bit value generated by a strong CSPRNG can provide a huge search space. But simply displaying 128 bits of output does not guarantee 128 bits of entropy if the underlying generator or seed is predictable.

Statistical Randomness Is Not Cryptographic Security

A PRNG can pass many statistical tests and still be unsuitable for security. Statistical tests examine whether output behaves according to expected mathematical properties. Cryptographic security additionally asks whether an attacker can exploit the generator's structure, state, seed, or implementation.

QuestionStatistical PRNGCSPRNG
Does output look random?Yes, ideallyYes
Is distribution quality important?YesYes
Can state potentially be recovered?PossiblyDesigned to resist
Can future values be predicted?May be possibleDesigned to prevent practical prediction
Safe for secrets?NoYes

Common PRNG Algorithms

Many PRNG families have been designed for different combinations of speed, memory usage, period length, and statistical quality.

FamilyTypical StrengthTypical Use
Linear Congruential GeneratorsSimple and fastTeaching and legacy systems
Mersenne TwisterVery long periodSimulation and modeling
Xorshift familyExtremely fastNon-security workloads
PCG familyGood statistical propertiesGeneral-purpose applications
CSPRNGsPrediction resistanceSecurity-sensitive applications

None of the traditional simulation-oriented PRNG families should automatically be treated as cryptographically secure just because their output looks random.

What Makes a CSPRNG Different?

A CSPRNG is designed around security requirements rather than only statistical quality. Its construction should make it difficult to infer internal state, predict future output, or reconstruct previous output from observations.

  • Strong and unpredictable initialization.
  • A secure internal state.
  • Resistance to state-recovery attacks.
  • Resistance to output prediction.
  • Careful handling of compromise and reseeding.
  • Well-studied cryptographic construction.

Forward and Backward Security

Security-oriented random generators may be designed so that learning some internal state does not automatically reveal all past or future output. These properties are commonly discussed as forward security and backward security, although the exact terminology and guarantees depend on the generator design.

The goal is to limit the damage caused by a state compromise rather than allowing one exposed state to reveal an unlimited amount of generated data.

Why Operating-System Randomness Matters

Modern operating systems provide cryptographic random interfaces that applications can use instead of building their own entropy collection systems. These interfaces are designed to provide unpredictable random bytes to applications.

Using a platform-provided cryptographic API is usually safer than combining timestamps, process IDs, counters, mouse movement, or other application-level values and assuming the result is secure.

JavaScript: Math.random() vs crypto.getRandomValues()

In browser JavaScript, Math.random() is intended for general-purpose pseudorandom values. It should not be used for passwords, authentication tokens, API keys, or cryptographic secrets.

// General-purpose PRNG
const value = Math.random();

// Cryptographically secure random bytes
const bytes = new Uint8Array(32);
crypto.getRandomValues(bytes);

The Web Crypto API provides cryptographic primitives designed for security-sensitive browser applications. Server-side JavaScript environments such as Node.js also provide cryptographic random APIs.

When to Use a PRNG

  • Simulations where reproducibility matters.
  • Procedural content generation.
  • Game mechanics that do not require cryptographic security.
  • Randomized tests.
  • Monte Carlo calculations.
  • Non-security randomized algorithms.

A PRNG is often the better engineering choice when security is irrelevant and performance or deterministic reproduction is important.

When to Use a CSPRNG

  • Password generation.
  • API key generation.
  • Session identifiers.
  • Password-reset tokens.
  • Email verification tokens.
  • Authentication challenges.
  • Cryptographic nonces.
  • Cryptographic key material.
  • Other values an attacker must not be able to predict.

Whenever guessing the next generated value could allow an attacker to access data or impersonate a user, a CSPRNG should be the default choice.

PRNGs in Simulations

Simulation software often benefits from deterministic randomness. A researcher can run an experiment with a known seed, record the results, and later reproduce the exact same sequence.

Experiment
    ↓
Seed = 123456
    ↓
PRNG
    ↓
Millions of generated values
    ↓
Simulation results

Run again with same seed
    ↓
Same sequence
    ↓
Reproducible results

CSPRNGs in Password Generation

Passwords generated automatically should use a cryptographically secure source of randomness. The generator should also choose characters without introducing significant bias.

For example, selecting a password character using a secure random integer from an appropriate range is preferable to taking an arbitrary random byte and applying modulo when the character set size does not divide the source range evenly.

CSPRNGs in API Key Generation

API keys are bearer credentials in many systems. Anyone who possesses a valid key may be able to access the associated API, so keys need enough unpredictability to make guessing infeasible.

CSPRNG
  ↓
Random bytes
  ↓
Base64url / hexadecimal encoding
  ↓
API key
  ↓
Stored and transmitted securely

The encoding used to display a key does not create entropy. It only represents the randomly generated bytes in a convenient textual format.

CSPRNGs in Session IDs

Session identifiers need strong unpredictability because an attacker who can guess another user's active session identifier may be able to impersonate that user.

A secure session identifier should therefore be generated from a CSPRNG and have sufficient effective entropy. Session security also requires secure cookie settings, expiration, rotation, transport protection, and proper server-side session handling.

Why 'Random-Looking' Is Not Enough

Humans are often poor at judging randomness visually. A sequence can look irregular while being generated by a completely deterministic algorithm. Conversely, a genuinely random sequence can contain repeated values or apparent patterns.

Security should therefore never be evaluated by looking at a few generated values. The generator's algorithm, entropy source, state management, and implementation are what matter.

Modulo Bias and Secure Random Selection

Even with a CSPRNG, an application can accidentally introduce bias when converting random bytes into a restricted range. The classic example is applying modulo directly to a random integer when the source range is not evenly divisible by the target range.

Random source: 0..255
Target:       0..99

256 is not evenly divisible by 100.

Using value % 100
can make some values more likely.

Rejection sampling avoids this problem by discarding source values from the uneven remainder and drawing another value. Many secure random APIs provide range-selection helpers so developers do not need to implement this logic manually.

Can a CSPRNG Be Reproducible?

Cryptographic generators are deterministic internally, but their security depends on keeping their state and entropy inputs protected. Reproducing a CSPRNG sequence intentionally is generally not the goal for application-level security.

If reproducibility is required for a simulation or test, a conventional seeded PRNG is normally a more appropriate choice.

Performance Differences

Traditional PRNGs can be extremely fast because their algorithms are optimized for generating large quantities of data. CSPRNGs perform additional security-related processing, but modern operating systems and cryptographic libraries are generally fast enough for ordinary application workloads.

For most applications, the performance difference should not justify replacing a CSPRNG with an insecure PRNG when the generated values protect something valuable.

Common Mistakes

  • Using Math.random() for passwords.
  • Using Math.random() for API keys.
  • Using a PRNG for session identifiers.
  • Seeding a security-sensitive generator with the current time.
  • Assuming a long PRNG period means cryptographic security.
  • Assuming passing statistical tests proves security.
  • Applying modulo without considering bias.
  • Building a custom CSPRNG instead of using a trusted cryptographic API.
  • Counting output characters instead of measuring effective entropy.
  • Logging random secrets or exposing generator state.

A Simple Decision Rule

Does an attacker benefit from predicting the value?
             │
       ┌─────┴─────┐
       │           │
      No          Yes
       │           │
      PRNG       CSPRNG

This is a useful starting rule. If predictability could affect security, authentication, authorization, confidentiality, or access to a valuable resource, use a cryptographically secure generator.

PRNG vs CSPRNG: Practical Examples

TaskRecommended ChoiceReason
Shuffle a list for a gamePRNGSecurity usually not required
Generate simulation dataPRNGReproducibility is useful
Generate procedural terrainSeeded PRNGDeterministic generation can be valuable
Generate a passwordCSPRNGPassword must be unpredictable
Generate an API keyCSPRNGKey guessing must be infeasible
Generate a session IDCSPRNGPredictability can enable account takeover
Generate a reset tokenCSPRNGToken protects account recovery
Generate a cryptographic keyCSPRNG / crypto APIKey security depends on unpredictability

Frequently Asked Questions

What is the difference between pseudorandom and cryptographically secure random?

A pseudorandom generator produces deterministic random-looking values, while a CSPRNG is specifically designed to make its output computationally difficult to predict or reconstruct.

Is a PRNG the same as a CSPRNG?

A CSPRNG is a type of pseudorandom generator, but it provides additional security properties designed to resist prediction and state-recovery attacks.

When should I use a PRNG?

Use a conventional PRNG for simulations, games, randomized testing, procedural generation, and other applications where cryptographic unpredictability is not required.

When should I use a CSPRNG?

Use a CSPRNG whenever an attacker must not be able to predict the generated value, such as for passwords, API keys, session identifiers, reset tokens, and cryptographic keys.

Is Math.random() cryptographically secure?

No. Math.random() is intended for general-purpose pseudorandomness and should not be used to generate passwords, API keys, session tokens, or other security-sensitive values.

Can a predictable seed make random numbers insecure?

Yes. If a conventional PRNG is initialized with a predictable seed, an attacker may be able to reproduce its sequence and predict future values.

Why is entropy important for secure randomness?

Entropy represents unpredictability in a randomness source. Security-sensitive values need sufficient effective entropy so that guessing or searching their possible values is computationally infeasible.

Are CSPRNGs slower than regular PRNGs?

CSPRNGs can have more computational overhead than simple PRNGs, but modern operating systems and cryptographic libraries generally make secure randomness fast enough for most application security requirements.

Useful Randomness Tools

Use the Random Number Generator for ordinary numeric randomness, the Secure Random Generator when cryptographic unpredictability is required, and the Entropy Calculator to estimate the size of a possible value space. For practical security-sensitive generation, API Key Generator and Password Generator tools should rely on secure random sources rather than ordinary PRNGs.

Conclusion

Pseudorandom and cryptographically secure random generators solve different problems. A PRNG is deterministic, fast, and often ideal for simulations, games, testing, and reproducible randomized workloads. A CSPRNG is designed to provide unpredictable output suitable for security-sensitive applications.

The most important question is not whether a sequence looks random, but whether an attacker could predict it. If the answer could affect authentication, authorization, passwords, API access, or cryptographic security, use a trusted CSPRNG provided by the operating system or a reputable cryptographic library.

Found an issue?

Found an error, outdated information, or something missing from this article? Let me know through the Contact page.

Your feedback helps improve our articles and keep them accurate and useful.