random_bytes()
debt(d5/e1/b2/t7)
Closest to 'specialist tool catches' (d5), semgrep/psalm/phpstan rules can flag mt_rand()/rand()/uniqid() in security contexts, but default configs often miss it without security-focused rulesets.
Closest to 'one-line patch or single-call swap' (e1), quick_fix is literally replacing mt_rand() with random_bytes(32) — a direct call substitution.
Closest to 'localised tax' (b3), minus one toward minimal — using random_bytes is a trivial standard-library call with no architectural weight; the choice is local to each token-generation site.
Closest to 'serious trap' (t7), the misconception is explicit: developers reasonably believe mt_rand() is 'random enough' because the name and ubiquity suggest general-purpose randomness, but it's predictable and catastrophic for security — the obvious choice is wrong.
Also Known As
TL;DR
Explanation
random_bytes(int $length) returns a string of $length cryptographically random bytes sourced from /dev/urandom (Linux/macOS) or CryptGenRandom (Windows). bin2hex(random_bytes(32)) produces a 64-character hex token with 256 bits of entropy — unguessable in practice. Use it for password reset tokens, API keys, CSRF tokens, and any other security-sensitive random value. Never use rand(), mt_rand(), or uniqid() for these purposes.
Common Misconception
Why It Matters
Common Mistakes
- Using rand(), mt_rand(), or array_rand() for security purposes — they are seeded by time and predictable.
- Using uniqid() for tokens — it is based on microtime and has insufficient entropy.
- Not hex-encoding or base64-encoding the output before storage — raw bytes may contain null bytes.
- Requesting fewer bytes than needed — 16 bytes (128 bits) is the minimum for security tokens; 32 bytes (256 bits) is better.
Code Examples
// Predictable token generation:
$token = md5(uniqid(mt_rand(), true)); // Guessable — time-based entropy
$token = sha1(rand()); // rand() is not cryptographically secure
// Correct:
$token = bin2hex(random_bytes(32)); // 256 bits of CSPRNG entropy
// Cryptographically secure random bytes (PHP 7+)
$token = random_bytes(32); // 32 bytes = 256 bits
$hex = bin2hex($token); // 64 hex chars
$b64 = base64_encode($token); // URL-safe: strtr(base64_encode($token), '+/', '-_')
// Secure random integer (e.g. OTP, random delay)
$otp = random_int(100000, 999999); // cryptographically secure
// NOT cryptographically secure — never use for tokens/secrets:
// mt_rand(), rand(), array_rand(), shuffle() — all predictable
// Password reset token
$resetToken = bin2hex(random_bytes(32)); // store hash in DB, send raw to user
$stored = hash('sha256', $resetToken);