Skip to content

Random Number Generators: How They Work and How to Use One

Nov 14, 2026 · Tooling

Quick answer: A random number generator is an algorithm or hardware source that produces values from a distribution. Pseudo-random generators use deterministic algorithms and seeds; true random generators draw unpredictable physical signals. For security-sensitive tasks such as keys, tokens, and nonces, use a cryptographically secure generator.

See also: AI Character Generators: How They Work and How to Choose · uuid validator · uuid v4 generator

Key takeaways

  • True vs. Pseudo —

Common mistakes to avoid

Several mistakes can make a random number generator unsuitable for its intended purpose, whether that means shuffling a list or generating cryptographic keys.

  • Using a non-cryptographic generator for secrets. Languages often provide fast, general-purpose APIs such as JavaScript’s Math.random(), but their outputs are predictable and should never protect passwords, session tokens, reset links, or encryption keys. Use platform cryptographic APIs instead, such as secrets or SystemRandom in Python, SecureRandom in Java, and crypto.randomBytes() or crypto.randomInt() in Node.js.
  • Creating a custom generator with insufficient entropy. Avoid seeding a generator only with the current time, a process ID, or another easily guessed value. For cryptographic applications, follow the operating system’s approved entropy source and relevant guidance, such as NIST SP 800-90A/B/C or a validated FIPS 140-validated module.
  • Ignoring modulo bias. Reducing randomInt() with value % bound can make some outcomes slightly more likely when the range does not divide evenly. APIs that accept an upper bound generally handle this rejection sampling internally.
  • Assuming reproducibility is compatible with secrecy. Recording a PRNG seed can make a sequence reproducible, but it may also let someone reconstruct every value produced afterward. Keep seeds and internal states out of logs, source control, and client-visible code.
  • Using random values directly as database identifiers. Randomness does not eliminate collision risk. Combine it with a suitable uniqueness strategy, such as a UUID or ULID, and enforce the required database constraints.
  • Overlooking error handling and concurrency. Cryptographic randomness can fail or block when the system cannot obtain sufficient entropy. Check returned errors, and avoid sharing mutable generator state across threads without proper synchronization.

How to choose the right option

Choose a random number generator based on whether the output affects security. For simulations, games, sampling, and general development, a standard pseudorandom number generator (PRNG) is usually sufficient. For passwords, session tokens, API keys, encryption keys, nonce generation, and other security-sensitive values, use a cryptographically secure pseudorandom number generator (CSPRNG).

Language PRNG Games, testing, simulations Usually fast and reproducible from a seed
Operating-system CSPRNG Secrets and cryptography Examples include Linux getrandom(2), Windows CNG, and macOS arc4random_buf
Language security API Application secrets Use Python secrets, Java SecureRandom, Node.js crypto.randomBytes, or Go crypto/rand
Hardware RNG Centralized or high-assurance systems Check the device, driver, health checks, and applicable validation requirements
  • Prefer built-in platform security APIs over implementing cryptographic randomness yourself. They are designed to avoid common mistakes such as predictable seeds, insufficient entropy, or biased output.
  • If your environment requires approved cryptographic algorithms, review NIST SP 800-90B and the related NIST SP 800-90A and SP 800-90C recommendations.
  • Use rejection sampling when mapping random bits into a smaller range; a simple modulo operation can introduce bias.

For reproducible test data, record the algorithm and seed, but treat that combination as unsuitable for production credentials.

What to expect in 2026 and beyond

Random number generation in 2026 will increasingly focus on cryptographically secure randomness rather than statistical uniformity alone. For security-sensitive uses—session tokens, password resets, key material, nonces, and identifiers—applications should use a cryptographically secure pseudorandom number generator (CSPRNG), not a general-purpose random function.

  • Web applications: Use the browser’s Web Crypto API, especially crypto.getRandomValues(). For UUIDs, crypto.randomUUID() generates a version 4 UUID using secure randomness.
  • Node.js: The crypto module provides randomInt(), randomBytes(), and randomUUID(). These are appropriate for secrets and security tokens.
  • Python: Use secrets for passwords, tokens, and cryptographic keys. The standard random module is designed for simulation, not security.
  • Java: Prefer java.security.SecureRandom for cryptographic operations.
  • Go: Use crypto/rand, including rand.Int and rand.Read, when unguessable output matters.
Requirement Recommended tool Primary standard or guarantee
Simulation and sampling Python random, JavaScript Math.random() Fast, non-cryptographic output
Application secrets Web Crypto, Node.js crypto, Python secrets Operating-system-backed CSPRNG
Cryptographic algorithms NIST-approved DRBGs NIST SP 800-90A, 90B, and 90C

Expect stronger guidance around entropy sourcing, reproducible testing, and post-quantum migration. Regulated deployments may also need validated cryptographic modules under NIST FIPS 140-3.

What drives the cost

The cost of a random number generator is rarely determined by the number of values it produces. Most implementations have no per-call fee; the real costs come from security, infrastructure, engineering, and ongoing support.

  • Entropy and implementation: A cryptographically secure generator needs reliable entropy, secure seeding, and a well-reviewed algorithm. Standards such as NIST SP 800-90A, SP 800-90B, and SP 800-90C define suitable approaches and testing requirements.
  • Security and compliance: Applications generating tokens, session identifiers, keys, or password-reset codes need a cryptographically secure random number generator. Hardware-backed or certified modules can add equipment, validation, and compliance costs.
  • Scale

    Frequently asked questions

    What is a random number generator (RNG)?

    A random number generator, or RNG, is an algorithm or system that produces values intended to appear unrelated to one another. Some RNGs are deterministic pseudorandom number generators (PRNGs), while others use physical entropy sources to create cryptographically secure random values. The right choice depends on whether you need reproducibility, statistical randomness, or security.

    What is the difference between a PRNG and a cryptographically secure RNG?

    A PRNG uses a deterministic algorithm and an initial seed to produce a reproducible sequence, making it useful for simulations, games, and tests. A cryptographically secure RNG, such as Python’s `secrets` module or JavaScript’s `crypto.getRandomValues()`, is designed to resist prediction when generating keys, tokens, and other sensitive values. Do not use a general-purpose PRNG for passwords, cryptographic keys, or session identifiers.

    Which programming languages have built-in random number generators?

    Python provides `random` for general-purpose pseudorandom values and `secrets` for security-sensitive values. JavaScript exposes `Math.random()` for non-cryptographic use and the Web Crypto API for cryptographically secure bytes, while browsers and operating systems also offer platform-specific secure-random interfaces. Check the language and runtime documentation because the guarantees differ between APIs.

    How do I generate a random number in Python?

    Use `random.randint(a, b)` for an inclusive integer or `random.uniform(a, b)` for a floating-point value in a general-purpose program. For security-sensitive material, use `secrets.randbelow(n)` to generate an integer below a limit without modulo bias. The `random` module is not appropriate for cryptographic keys or unpredictable authentication tokens.

    How do I generate random numbers in JavaScript?

    `Math.floor(Math.random() * max)` is common for non-security-sensitive integers within a specified range, although its output is predictable and should not protect secrets. Use `crypto.getRandomValues()` to fill a typed array with secure random bytes, then apply a rejection-sampling method if you need an unbiased integer range. Node.js applications can also use the `crypto` module documented by the Node.js project.

    How do I make a random number generator reproducible?

    Initialize a PRNG with a fixed seed and record that seed alongside the results. Python’s `random.Random(seed)` and JavaScript libraries such as SeedRandom can create repeatable sequences, but the algorithms, libraries, and versions may affect exact output.

    Are random numbers truly random?

    Computer-generated values are usually pseudorandom: a deterministic algorithm expands an internal state into a sequence that appears random for a specific purpose. Hardware-assisted secure RNGs draw unpredictable entropy from physical or platform-provided sources, then condition and distribute it for cryptographic use. A generator that is statistically useful for simulations is not automatically suitable for security.

    Why can some random-number methods introduce bias?

    Bias appears when a continuous random value is mapped onto a discrete range that does not divide evenly, causing some outcomes to have a slightly higher probability. Techniques such as rejection sampling, Lemire’s method, or integer arithmetic designed for unbiased bounded generation can prevent this problem. Cryptographic APIs may return bytes or arbitrary bit strings, so application code must implement range conversion correctly.

    When should I use a random number generator in software?

    Use a PRNG for simulations, shuffling, sampling, procedural content, and load distribution where repeatable behavior is acceptable. Use a cryptographically secure RNG for API keys, password reset tokens, nonces, salts, and other values that an attacker might predict. For standards-sensitive work, consult official specifications such as NIST’s cryptographic guidance or the relevant language and platform documentation.

    Tom Reed

    About the author

    Tom Reed

    Developer Tools Writer

    Tom Reed covers developer utilities and online tools at QuikConsole, focusing on how they work and where they fit into real workflows.


Contact: contact@quikconsolecom.net