Skip to content
Why rand() is Predictable
step 1/5

Reading — step 1 of 5

Read

~1 min readWhat's Wrong with rand()

Why rand() is Predictable

Most languages' built-in random functions are NOT cryptographically secure:

// C
srand(time(NULL));
int x = rand();   // predictable from time

// Python
import random
random.random()  // Mersenne Twister; predictable from 624 outputs

These use pseudo-random number generators (PRNGs) — deterministic algorithms producing seemingly-random output from a SEED. Given the seed, all output is reproducible.

Example: Mersenne Twister (Python's random):

  • 19937-bit internal state
  • Once an attacker observes 624 32-bit outputs, they can SOLVE for the state and predict ALL future output

Why is this OK for some uses?

  • Simulations (need reproducibility)
  • Games (just feel-random)
  • Hash table seed (within trusted process)

NOT OK for:

  • Crypto keys
  • Session tokens
  • Password reset tokens
  • IV/nonce for encryption
  • ANY security-relevant value

For security: use CSPRNG (Cryptographically Secure PRNG). The OS provides one:

  • Linux: /dev/urandom or getrandom()
  • macOS: /dev/urandom or arc4random
  • Windows: BCryptGenRandom
  • Java: SecureRandom
  • Python: secrets module
  • Node: crypto.randomBytes()

Discussion

Ask a question, share an insight, or help someone who’s stuck.

Sign in to post a comment or reply.

Loading…