{"record":{"id":"ec71e01e4a115966","repo":"paragonie/random_compat","slug":"random-bytes-bytes-must-be-an-integer-libsodium-legacy","errorCode":null,"errorMessage":"random_bytes(): $bytes must be an integer","messagePattern":"random_bytes\\(\\): \\$bytes must be an integer","errorType":"exception","errorClass":"TypeError","httpStatus":null,"severity":"error","filePath":"lib/random_bytes_libsodium_legacy.php","lineNumber":49,"sourceCode":"     * If the libsodium PHP extension is loaded, we'll use it above any other\n     * solution.\n     *\n     * libsodium-php project:\n     * @ref https://github.com/jedisct1/libsodium-php\n     *\n     * @param int $bytes\n     *\n     * @throws Exception\n     *\n     * @return string\n     */\n    function random_bytes($bytes)\n    {\n        try {\n            /** @var int $bytes */\n            $bytes = RandomCompat_intval($bytes);\n        } catch (TypeError $ex) {\n            throw new TypeError(\n                'random_bytes(): $bytes must be an integer'\n            );\n        }\n\n        if ($bytes < 1) {\n            throw new Error(\n                'Length must be greater than 0'\n            );\n        }\n\n        /**\n         * @var string\n         */\n        $buf = '';\n\n        /**\n         * \\Sodium\\randombytes_buf() doesn't allow more than 2147483647 bytes to be\n         * generated in one invocation.","sourceCodeStart":31,"sourceCodeEnd":67,"githubUrl":"https://github.com/paragonie/random_compat/blob/b5d188cc9d5e02f94d2c41da23093f1ef557c5b1/lib/random_bytes_libsodium_legacy.php#L31-L67","documentation":"random_compat's libsodium-legacy random_bytes() first coerces its $bytes argument with RandomCompat_intval(); if the value cannot be represented as an integer (floats with fractional parts, non-numeric strings, objects), a TypeError is caught and re-thrown with this message. The library enforces strict integer input even on PHP 5, mirroring PHP 7's random_bytes() signature.","triggerScenarios":"Calling random_bytes() with a non-integer value such as '32', 32.5, null, or an array — RandomCompat_intval() throws and lib/random_bytes_libsodium_legacy.php:49 rethrows as TypeError.","commonSituations":"Passing a string from user input or a config file without casting, passing the result of division on PHP 5 where floats are common, or passing null from an uninitialized variable.","solutions":["Cast the argument explicitly to int before calling: random_bytes((int) $length).","Validate the input is a whole number (is_int() or ctype_digit for strings) before calling.","If the value comes from user input, reject non-numeric input rather than silently casting.","Update code paths that compute lengths with float math to use intval() or (int) casts."],"exampleFix":"// before\n$bytes = random_bytes($_GET['length']);\n// after\n$length = filter_var($_GET['length'], FILTER_VALIDATE_INT);\nif ($length === false || $length < 1) {\n    throw new InvalidArgumentException('length must be a positive integer');\n}\n$bytes = random_bytes($length);","handlingStrategy":"type-guard","validationCode":"function isValidByteLength($n): bool {\n    return is_int($n) && $n >= 1;\n}","typeGuard":"function asByteCount($n): ?int {\n    if (is_int($n) && $n >= 1) return $n;\n    if (is_string($n) && ctype_digit($n)) return (int) $n;\n    return null; // caller must handle\n}","tryCatchPattern":"try {\n    $bytes = random_bytes($length);\n} catch (TypeError $e) {\n    throw new InvalidArgumentException('$length must be an integer >= 1', 0, $e);\n}","preventionTips":["Cast lengths with (int) only after validating the raw value is numeric.","Use filter_var($v, FILTER_VALIDATE_INT) for user-supplied lengths.","On PHP 7+, add int type declarations to wrapper functions.","Never pass untyped superglobal values directly to random_bytes()."],"tags":["php","typeerror","argument-validation","randomness"],"backgroundTag":"type-mismatch","analyzedSha":"b5d188cc9d5e02f94d2c41da23093f1ef557c5b1","analyzedAt":"2026-09-13T16:12:09.755Z","contentChangedAt":"2026-09-13T16:12:09.755Z","schemaVersion":2},"datasetVersion":"2026-09-16T04:17:20.429Z"}