---
title: Reference Tokens 128-bit Entropy CSPRNG
impact: HIGH
impactDescription: prevents token prediction and brute-force attacks
tags: tokens, entropy, csprng, session, security, php
---

## Reference Tokens 128-bit Entropy CSPRNG

Predictable or low-entropy tokens (API keys, session IDs, reset tokens) can be guessed or brute-forced. Using a Cryptographically Secure Pseudo-Random Number Generator (CSPRNG) with at least 128 bits of entropy makes such attacks computationally infeasible.

**Incorrect (predictable or low-entropy tokens):**

```php
// 1. Predictable - using non-CS PRNG
$token = uniqid(); // Based on microtime, highly predictable

// 2. Predictable - Sequential or timestamp based
$token = "session_" . time() . "_" . $userId;

// 3. Low Entropy
$token = bin2hex(random_bytes(4)); // Only 32 bits of entropy
```

**Correct (high-entropy CSPRNG tokens):**

```php
// 1. Minimum 128 bits (16 bytes = 128 bits)
$sessionToken = bin2hex(random_bytes(16));

// 2. Recommended 256 bits (32 bytes)
$apiKey = 'sk_' . bin2hex(random_bytes(32));

// 3. Using Base64 (URL safe) for better efficiency
$token = str_replace(['+', '/', '='], ['-', '_', ''], base64_encode(random_bytes(32)));

/**
 * 4. Using Laravel Helpers (Powered by random_bytes)
 */
use Illuminate\Support\Str;

$token = Str::random(40); // Generates a random alphanumeric string
```

**Entropy Guide:**

| Bytes | Bits | Use Case |
|-------|------|----------|
| 8 | 64 | **Weak** (Guessable in small datasets) |
| 16 | 128 | **Minimum** for session IDs |
| 32 | 256 | **Recommended** for API keys & Refresh Tokens |

**Key Rules:**
- **Always use `random_bytes()`** or `random_int()` in PHP.
- **Never use `rand()`**, `mt_rand()`, or `uniqid()` for security tokens.
- **Encode securely**: Use `bin2hex` or URL-safe Base64 for token representation.

**Tools:** PHP Internal `random_bytes()`, SonarQube, Manual Security Review
