← Back to section · Tutorials & Labs
Getting Randomness Right in Code: Secure Random Entry Points by Language and Common Misuses
Randomness is the source of keys, nonces, and tokens. This article lists, by language, the cryptographically secure random entry points you should use, explains how OS entropy sources work, and catalogs the classic failures of timestamps, ordinary PRNGs, and bad seeding.
A great deal of cryptographic security ultimately rests on randomness: keys must be random, initialization vectors must be random, and session tokens, verification codes, and password reset links must all be random. Once randomness becomes predictable, no strength of algorithm can save you — the attacker does not need to break the algorithm, only to guess the “random” numbers you used when generating the key. Many famous incidents in history, from an early browser whose random seeds were just time and process ID, to a wallet that generated repeated signature randomness because of a broken random source, were not algorithm breaks at all, but randomness that was guessed or repeated. This article gives rules you can apply directly: which entry points to draw randomness from, why those entry points are trustworthy, and which patterns must be removed from your code.
First, distinguish the two kinds of random number generators
Ordinary pseudorandom number generators (such as most languages’ random module, Math.random, or rand()) are designed for output that looks statistically well-distributed, runs fast, and suits simulation experiments; once an observer sees a small slice of their output, their internal state lets all subsequent output be computed. These generators are fine for shuffle animations and Monte Carlo simulation, and must never be used for any security purpose.
Cryptographically secure random number generators have a completely different requirement: output must be unpredictable, so that even an attacker who sees the entire history cannot infer the next bit. The only reliable engineering approach is to ask the operating system: the kernel continuously collects entropy from hardware interrupt timings, device noise, and similar sources, maintains an entropy pool, and exposes it through dedicated interfaces. An application collecting mouse movements on its own, cobbling together its own seeds, or implementing its own entropy pool is reinventing a worse wheel. The rule is one sentence: secure randomness comes only from operating system interfaces — never build your own, never take a detour.
The secure entry points, by language
Here is the table for common languages; check against it as you write code. Python: the standard library secrets module is designed for tokens and keys and is backed by the OS source; os.urandom is equally trustworthy; never use the random module for any credential. Java and Kotlin: java.security.SecureRandom, with the default constructor; do not supply your own seed. Go: the Reader in the crypto/rand package, strictly distinguished from math/rand — the latter must be caught by comments and code review. JavaScript and Node: crypto.getRandomValues in the browser, crypto.randomBytes in Node; Math.random never enters security code. Rust: OsRng from the rand ecosystem, or a thread-safe generator built on it. C and C++: call platform interfaces directly, such as the getrandom system call or reading /dev/urandom on Linux, or use the random facilities of a mature crypto library; rand() with srand(time(0)) is the textbook counterexample.
Checkpoints: search the codebase globally for the names of ordinary random interfaces and confirm, call site by call site, that none of them serve a security purpose; wrap secure randomness in a single project-wide function or module so business code only calls the wrapper and never touches the low-level interface directly — then future audits and replacements have exactly one place to look.
Length and purpose: randomness is sized by calculation, not by “longer is better”
Generating random bytes is only the first step; using the right length for the right scenario matters just as much. Credentials where a correct guess means impersonation — session tokens and API keys — should carry at least 128 bits of randomness: below that, the cost of offline bulk guessing enters an affordable range for attackers. Symmetric keys take the full length the algorithm requires — a full 32 bytes for AES-256 — and a password string must never be used directly as a key, since a password’s entropy is far below that of random bytes of the same length; when derivation from a password is genuinely needed, use a proper password hashing / key derivation function with a random salt.
Nonce and IV requirements vary by algorithm: most scenarios need uniqueness rather than unpredictability, but generating them from a secure random source is the most worry-free way to get uniqueness, provided the length makes collision probability negligible. When converting random bytes to strings, use hexadecimal or Base64 encoding; do not map by modulo into a character set — modulo introduces distributional bias whenever the character set size is not a power of two, and that bias is left for the attacker.
Three misuse patterns that must go
First, seeding any generator with guessable information such as timestamps, process IDs, or machine names: the entropy of these values combined cannot support a single key generation. Second, generating randomness inside contexts that can be replayed: virtual machine snapshot restores, containers cloned in bulk from one image, and child processes inheriting generator state after fork can all cause two places to produce the same “random” sequence; the countermeasure is to draw fresh from the operating system each time, rather than drawing a large pool at process start and spending it slowly. Third, replacing secure randomness with a fixed seed in test code for convenience, while letting that replacement logic leak into production builds — test doubles must be isolated by build configuration and specifically verified in the release checklist.
A common question: should I gather my own entropy?
Developers often worry that the OS entropy source “might not be enough” and want to add something to the pool themselves — stirring in time, network jitter, and user input as seed. On modern operating systems this worry is basically unnecessary: the kernel entropy pool is designed for continuous supply, and normal application consumption comes nowhere near exhausting it. The risks of self-seeding, by contrast, are real: predictable inputs drag down overall quality, and a wrong mixing method can pollute an otherwise healthy entropy source. The conclusion matches everything above: draw directly from the system interface on demand; do not seed, do not hoard a pool, do not brew your own entropy. In genuinely special situations such as embedded devices with insufficient entropy at early boot, the correct solution is the entropy solution and readiness-check interfaces provided by the chip vendor and the system — not an application-layer collection scheme invented on the spot.
Wrap-up: four questions for a randomness audit
When reviewing code that involves randomness, ask four questions: does the source come from a secure entry point backed by the OS entropy source; was the length calculated for its purpose or chosen casually; is there any repetition risk under snapshot, clone, or fork scenarios; and does the string encoding introduce distributional bias. If all four can be answered well, the code’s randomness is used correctly — it is the foundation beneath every key, token, and protocol freshness guarantee, and if the foundation is crooked, no elegant algorithm tower built on it will stand.
Tags: RandomnessEntropy SourcesSecure CodingKey Generation