---
title: Use CSPRNG For Security Purposes
impact: HIGH
impactDescription: prevents predictable tokens and session hijacking
tags: random, csprng, tokens, session, cryptography, security, php
---

## Use CSPRNG For Security Purposes

Non-cryptographic random generators like `rand()` or `mt_rand()` are predictable. Attackers can guess session tokens, OTPs, and password reset links if they are generated with weak random sources.

**Incorrect (predictable random):**

```php
// INSECURE - predictable!
$sessionId = md5(rand());

// INSECURE - mt_rand() is faster but not cryptographically secure
$otp = mt_rand(100000, 999999);

// INSECURE - uniqid() is based on current time in microseconds
$resetToken = uniqid('token_', true);
```

**Correct (cryptographically secure):**

```php
// Cryptographically secure session ID or token
$token = bin2hex(random_bytes(32)); // 256-bit entropy

// Secure OTP generation
$otp = random_int(100000, 999999);

// Using Laravel's Str helper (which uses random_bytes internally)
use Illuminate\Support\Str;
$token = Str::random(40);
```

**CSPRNG by language (Update):**

| Language | Secure | Insecure |
|----------|--------|----------|
| PHP7+    | `random_bytes()`, `random_int()` | `rand()`, `mt_rand()`, `uniqid()` |
| Node.js  | `crypto.randomBytes()` | `Math.random()` |
| Python   | `secrets`, `os.urandom()` | `random` |

**Tools:** PHPStan (extension-installer), Psalm, SonarQube (S2245), Semgrep
