← Home ← Codex ← DEBT
Browse by Category
+ added · updated 7d
← Back to glossary

random_bytes()

PHP PHP 7.0+ Intermediate
debt(d5/e1/b2/t7)
d5 Detectability Operational debt — how invisible misuse is to your safety net

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.

e1 Effort Remediation debt — work required to fix once spotted

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.

b2 Burden Structural debt — long-term weight of choosing wrong

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.

t7 Trap Cognitive debt — how counter-intuitive correct behaviour is

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.

About DEBT scoring →

Also Known As

random_bytes() random_int() CSPRNG PHP

TL;DR

Generates cryptographically secure random bytes from the OS entropy source — use for tokens, salts, and nonces.

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

rand() and mt_rand() are sufficient for generating tokens and nonces. Both are seeded PRNGs predictable from enough observed output. random_bytes() pulls from the OS entropy pool and is the only correct choice for security-sensitive randomness in PHP.

Why It Matters

random_bytes() generates cryptographically secure random bytes using the OS entropy source — it is the correct foundation for tokens, salts, IVs, and any security-sensitive random value in PHP 7+.

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

✗ Vulnerable
// 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
✓ Fixed
// 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);

Added 15 Mar 2026
Edited 22 Mar 2026
Views 55
Rate this term
No ratings yet
🤖 AI Guestbook educational data only
| |
Last 30 days
1 ping T 1 ping W 1 ping T 0 pings F 0 pings S 0 pings S 0 pings M 0 pings T 1 ping W 1 ping T 0 pings F 1 ping S 3 pings S 3 pings M 2 pings T 0 pings W 0 pings T 0 pings F 0 pings S 0 pings S 0 pings M 1 ping T 0 pings W 0 pings T 0 pings F 0 pings S 2 pings S 0 pings M 1 ping T 0 pings W
No pings yet today
Bing 1
Scrapy 10 Amazonbot 7 Ahrefs 6 SEMrush 5 Perplexity 4 Google 3 Unknown AI 2 Claude 2 Bing 2 ChatGPT 2 Meta AI 1 PetalBot 1
crawler 41 crawler_json 4
DEV INTEL Tools & Severity
🔴 Critical ⚙ Fix effort: Low
⚡ Quick Fix
Use random_bytes(32) for all cryptographic randomness — it reads from /dev/urandom on Linux and is guaranteed cryptographically secure; never use mt_rand(), rand(), or uniqid() for security
📦 Applies To
PHP 7.0+ web cli queue-worker
🔗 Prerequisites
🔍 Detection Hints
mt_rand() or rand() for token generation; uniqid() for session tokens; time()-based random seeds; md5(microtime()) as random token
Auto-detectable: ✓ Yes semgrep psalm phpstan
⚠ Related Problems
🤖 AI Agent
Confidence: High False Positives: Low ✓ Auto-fixable Fix: Low Context: Line
CWE-330 CWE-338


✓ schema.org compliant