Course contentsShow
← Security
Lesson 134 of 3,0523. Symmetric Cryptography Deep DiveFree lesson

Generating Secure Random IVs and Nonces

Learn proper methods for generating cryptographically secure random values using CSPRNGs and platform APIs.

Generating Secure Random IVs and Nonces

What you'll learn: You'll discover how to properly generate cryptographically secure random values for IVs and nonces using the right tools.

The Core Problem

Remember from earlier lessons that IVs and nonces must be unpredictable to prevent attacks like nonce reuse in CTR/GCM modes. But where do these random values actually come from? Not all "random" is created equal—using weak randomness is like locking your door but leaving the key under the mat.

CSPRNGs: Your Secure Random Source

A Cryptographically Secure Pseudo-Random Number Generator (CSPRNG) is a special algorithm designed to produce values that are:

  • Unpredictable: An attacker can't guess the next value even knowing previous ones
  • Uniformly distributed: All possible values are equally likely
  • Non-repeating: Extremely low probability of generating the same value twice

Think of a CSPRNG like a casino-grade dice roller versus shaking a pair of dice in your hand—one is engineered for true randomness, the other might have subtle patterns.

Platform APIs: The Right Way

Modern platforms provide battle-tested CSPRNGs:

  • Python: secrets.token_bytes() or os.urandom()
  • Node.js: crypto.randomBytes()
  • Java: SecureRandom
  • C#: RandomNumberGenerator.GetBytes()

Never use general-purpose random functions like Math.random(), rand(), or random.random()—these aren't cryptographically secure.

Practical Generation

For a 128-bit (16-byte) IV in CBC mode, you'd request 16 bytes from your platform's CSPRNG. Generate a fresh, random value for every encryption operation. Store or transmit it alongside your ciphertext (IVs aren't secret, just unpredictable).

Key Takeaway: Always use your platform's CSPRNG APIs (like secrets.token_bytes()) to generate IVs and nonces—never use standard random functions, as they lack cryptographic security properties.