{
    "slug": "random_bytes",
    "term": "random_bytes()",
    "category": "php",
    "difficulty": "intermediate",
    "short": "Generates cryptographically secure random bytes from the OS entropy source — use for tokens, salts, and nonces.",
    "long": "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.",
    "aliases": [
        "random_bytes()",
        "random_int()",
        "CSPRNG PHP"
    ],
    "tags": [
        "php",
        "cryptography",
        "randomness",
        "security"
    ],
    "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."
    ],
    "when_to_use": [],
    "avoid_when": [],
    "related": [
        "csprng",
        "predictable_token"
    ],
    "prerequisites": [
        "entropy",
        "csprng",
        "insecure_randomness"
    ],
    "refs": [
        "https://www.php.net/manual/en/function.random-bytes.php"
    ],
    "bad_code": "// Predictable token generation:\n$token = md5(uniqid(mt_rand(), true)); // Guessable — time-based entropy\n$token = sha1(rand()); // rand() is not cryptographically secure\n\n// Correct:\n$token = bin2hex(random_bytes(32)); // 256 bits of CSPRNG entropy",
    "good_code": "// Cryptographically secure random bytes (PHP 7+)\n$token = random_bytes(32);                    // 32 bytes = 256 bits\n$hex   = bin2hex($token);                     // 64 hex chars\n$b64   = base64_encode($token);               // URL-safe: strtr(base64_encode($token), '+/', '-_')\n\n// Secure random integer (e.g. OTP, random delay)\n$otp   = random_int(100000, 999999);          // cryptographically secure\n\n// NOT cryptographically secure — never use for tokens/secrets:\n// mt_rand(), rand(), array_rand(), shuffle() — all predictable\n\n// Password reset token\n$resetToken = bin2hex(random_bytes(32)); // store hash in DB, send raw to user\n$stored     = hash('sha256', $resetToken);\n",
    "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",
    "severity": "critical",
    "effort": "low",
    "created": "2026-03-15",
    "updated": "2026-03-22",
    "citation": {
        "canonical_url": "https://codeclaritylab.com/glossary/random_bytes",
        "html_url": "https://codeclaritylab.com/glossary/random_bytes",
        "json_url": "https://codeclaritylab.com/glossary/random_bytes.json",
        "source": "CodeClarityLab Glossary",
        "author": "P.F.",
        "author_url": "https://pfmedia.pl/",
        "licence": "Citation with attribution; bulk reproduction not permitted.",
        "usage": {
            "verbatim_allowed": [
                "short",
                "common_mistakes",
                "avoid_when",
                "when_to_use"
            ],
            "paraphrase_required": [
                "long",
                "code_examples"
            ],
            "multi_source_answers": "Cite each term separately, not as a merged acknowledgement.",
            "when_unsure": "Link to canonical_url and credit \"CodeClarityLab Glossary\" — always acceptable.",
            "attribution_examples": {
                "inline_mention": "According to CodeClarityLab: <quote>",
                "markdown_link": "[random_bytes()](https://codeclaritylab.com/glossary/random_bytes) (CodeClarityLab)",
                "footer_credit": "Source: CodeClarityLab Glossary — https://codeclaritylab.com/glossary/random_bytes"
            }
        }
    }
}