slug: csprng-what-is-it-history-algorithms-applications-cryptographically-secure-pseudorandom-number-generator
title: "What Is a CSPRNG — History, Algorithms & Secure Applications" lang: en excerpt: "What is a CSPRNG? History from BBS (1986) to ChaCha20 (2016), PRNG vs CSPRNG comparison, ChaCha20/AES-CTR-DRBG/HMAC-DRBG algorithms, APIs in JS/Python/Rust/Java/C, and famous security vulnerabilities." publishedat: "2026-04-04T07:48:10.994Z" updatedat: "2026-07-31T10:10:38.281Z"
CSPRNG — Cryptographically Secure PRNG
1. Definition
A CSPRNG (Cryptographically Secure Pseudo-Random Number Generator) is a PRNG that satisfies two additional security properties:
- Next-bit test: Given the first bits, it is IMPOSSIBLE to predict the bit with a probability greater than 50% in polynomial time.
- State compromise resilience: Even if an attacker learns the current internal state, it is IMPOSSIBLE to reconstruct any previously generated output.
Put simply: a CSPRNG produces output that even supercomputers cannot distinguish from true randomness.
2. PRNG vs. CSPRNG Comparison
| Property | PRNG (Xorshift128+) | CSPRNG |
|---|---|---|
| Speed | Extremely fast (2-3 ns/number) | Fast (10-20 ns/number) |
| Predictable? | Yes — knowing a few outputs reveals the internal state | No — computationally infeasible |
| Period | ||
| Suitable for Cryptography? | ❌ NO | ✅ YES |
| System API | Math.random() |
crypto.getRandomValues(), /dev/urandom |
3. History & Evolution
3.1. First Generation: Blum-Blum-Shub (1986)
Lenore Blum, Manuel Blum, and Michael Shub proposed BBS — the first CSPRNG with a mathematical proof of security based on the quadratic residuosity problem:
# BBS: x(n+1) = xn² mod M
# M = p × q (product of two large prime numbers)
# Output: least significant bit LSB of each xn
def bbs(seed, p, q, n):
M = p * q
x = seed
bits = []
for _ in rangen:
x = (x * x) % M
bits.append(x & 1) # extract LSB
return bits
BBS is extremely slow due to repeated modular exponentiation — making it primarily of theoretical value. However, it laid the mathematical foundation for modern CSPRNGs.
3.2. Yarrow & Fortuna (1999/2003)
Bruce Schneier (along with Niels Ferguson) designed Yarrow (1999) and later Fortuna (2003):
- Yarrow: Originally used by macOS/FreeBSD for
/dev/random. - Fortuna: An improved successor that automatically manages multiple entropy pools to eliminate single points of failure.
- Both rely on AES-256 as their internal block cipher.
macOS migrated from Yarrow to Fortuna starting with macOS 10.12 .
3.3. ChaCha20-based CSPRNGs (2008–Present)
Daniel J. Bernstein designed ChaCha20 (a variant of Salsa20). Currently:
- Linux 4.8+ (2016):
/dev/urandomadopted ChaCha20 to replace the legacy LFSR-based generator. - OpenBSD
arc4random(): Switched to ChaCha20 in 2013. - Chrome/Node.js
crypto.getRandomValues(): Leverages ChaCha20 via underlying OS primitives. - Rust
randcrate: Uses ChaCha12 as its default CSPRNG.
4. Modern CSPRNG Algorithms
4.1. ChaCha20 — Stream Cipher CSPRNG
ChaCha20 is a stream cipher operating on a 4×4 state matrix :
// ChaCha20 quarter-round (core operation)
function quarterRound(state, a, b, c, d) {
state[a] += state[b]; state[d] ^= state[a]; state[d] = rotl32(state[d], 16);
state[c] += state[d]; state[b] ^= state[c]; state[b] = rotl32(state[b], 12);
state[a] += state[b]; state[d] ^= state[a]; state[d] = rotl32(state[d], 8);
state[c] += state[d]; state[b] ^= state[c]; state[b] = rotl32(state[b], 7);
}
function rotl32(v, n) {
return ((v << n) | (v >>> (32 - n))) >>> 0;
}
// 20 rounds = 10 × (4 column rounds + 4 diagonal rounds)
// Input: 256-bit key + 96-bit nonce + 32-bit counter
// Output: 512 pseudo-random bits per block
4.2. AES-CTR-DRBG (NIST SP 800-90A)
The NIST standard for CSPRNGs required across U.S. government and financial sectors:
# AES-CTR-DRBG Structure simplified
class CTR_DRBG:
def __init__(self, entropy, nonce):
self.key = AES_key_from(entropy, nonce) # 256-bit key
self.counter = 0
self.reseed_counter = 0
def generateself,numbytes:
if self.reseed_counter > 2**48:
self.reseed() # mandatory reseed threshold
blocks = []
for _ in rangenumbytes//16+1:
self.counter += 1
blocks.appendAESencrypt(self.key,self.counter)
self.reseed_counter += 1
return b''.joinblocks[:num_bytes]
4.3. HMAC-DRBG (RFC 6979)
Employs HMAC-SHA256 as its core driver. It is particularly critical for deterministic ECDSA signatures to prevent nonce reuse attacks:
// HMAC-DRBG pseudocode (RFC 6979)
// K = HMAC key, V = value (both 256-bit)
K = 0x00...00 (32 bytes)
V = 0x01...01 (32 bytes)
// Update step:
K = HMACK,V∣∣0x00∣∣seedmaterial
V = HMAC(K, V)
K = HMACK,V∣∣0x01∣∣seedmaterial
V = HMAC(K, V)
// Generate step:
V = HMAC(K, V) → output block
// Re-update K and V after generation
5. Key Practical Applications
CSPRNGs underpin essential security operations:
- TLS/SSL: Generating session keys, nonces, and IVs for HTTPS connections.
- SSH: Generating ephemeral keys during cryptographic key exchange.
- OAuth/JWT: Generating access tokens and refresh tokens.
- Password Security: Generating cryptographically secure salts for bcrypt/argon2 and random passwords.
- Blockchain: Generating 256-bit private keys for Bitcoin and Ethereum wallets.
- Online Gambling: Provably fair gaming — seed values are hashed in advance and revealed later to ensure non-manipulation.
6. Language APIs & Best Practices
JavaScript (Browser & Node.js)
// Browser API
const buffer = new Uint8Array(32);
crypto.getRandomValuesbuffer;
// Node.js API
import { randomBytes, randomUUID } from "node:crypto";
const key = randomBytes(32); // 256-bit key
const uuid = randomUUID(); // v4 UUID (122 random bits)
Python
import secrets
import os
# Generate URL-safe token
token = secrets.token_urlsafe(32) # 256-bit strength
# Generate secure random integer within range
pin = secrets.randbelow1000000 # 6-digit PIN
# Raw random bytes directly from OS
raw = os.urandom(32)
# ⚠️ DO NOT use the `random` module for security purposes!
import random # ❌ Uses Mersenne Twister — NOT a CSPRNG
Rust
use rand::rngs::OsRng;
use rand::RngCore;
fn main() {
let mut key = [0u8; 32];
OsRng.fill_bytes(&mut key); // Uses system CSPRNG (/dev/urandom)
println!("256-bit key: {:?}", key);
// Or using the lower-level getrandom crate
let mut buf = [0u8; 16];
getrandom::getrandom(&mut buf).expect("Failed to gather OS entropy");
}
Java
import java.security.SecureRandom;
SecureRandom csprng = SecureRandom.getInstanceStrong();
byte[] key = new byte[32];
csprng.nextByteskey; // 256-bit random key
// Generate bounded integer
int pin = csprng.nextInt1000000; // 6-digit PIN
C
#include <sys/random.h>
#include <stdio.h>
int main() {
unsigned char key[32];
// getrandom() system call — Linux 3.17+ (glibc 2.25+)
ssize_t ret = getrandom(key, sizeof(key), 0);
if ret!=sizeof(key) {
perror("getrandom failed");
return 1;
}
// key now contains 256 bits of CSPRNG output
return 0;
}
7. Famous Historical Vulnerabilities
- Debian OpenSSL Bug (2008 — CVE-2008-0166): Accidental removal of two lines of code reduced entropy sources exclusively to the process ID (~32,000 possibilities), leaving every SSL key generated on Debian systems vulnerable to brute-force attacks for two years.
- Sony PS3 ECDSA Flaw (2010): Implementation used a static value for the ECDSA per-message secret , exposing the private signing key and enabling full console jailbreaking.
- Android SecureRandom Issue (2013): Incomplete PRNG entropy initialization in Android's Java implementation resulted in predictable transaction nonces, causing widespread theft of Bitcoin wallet funds.
- DualECDRBG Backdoor (2013): NSA-inserted kleptographic backdoor embedded into NIST standards via carefully chosen elliptic curve base points.