{"record":{"id":"315eca53e2b1712f","repo":"paragonie/random_compat","slug":"length-must-be-greater-than-0-random-bytes-libsodium-legacy","errorCode":null,"errorMessage":"Length must be greater than 0","messagePattern":"Length must be greater than 0","errorType":"exception","errorClass":"Error","httpStatus":null,"severity":"error","filePath":"lib/random_bytes_libsodium_legacy.php","lineNumber":55,"sourceCode":"     * @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.\n         */\n        if ($bytes > 2147483647) {\n            for ($i = 0; $i < $bytes; $i += 1073741824) {\n                $n = ($bytes - $i) > 1073741824\n                    ? 1073741824\n                    : $bytes - $i;","sourceCodeStart":37,"sourceCodeEnd":73,"githubUrl":"https://github.com/paragonie/random_compat/blob/b5d188cc9d5e02f94d2c41da23093f1ef557c5b1/lib/random_bytes_libsodium_legacy.php#L37-L73","documentation":"After confirming $bytes is an integer, random_compat's libsodium-legacy random_bytes() rejects values less than 1 with this Error. Zero or negative lengths are considered invalid input because a random-byte buffer must contain at least one byte, matching PHP 7's built-in behavior.","triggerScenarios":"Calling random_bytes(0) or random_bytes(-16) (e.g. a computed length from subtraction or an empty config value) triggers the '$bytes < 1' check at lib/random_bytes_libsodium_legacy.php:55.","commonSituations":"Length computed as strlen($a)-strlen($b) yielding 0, a config value defaulting to 0, or a caller that only guards against negative numbers but not zero.","solutions":["Guard the argument: if ($length < 1) throw/handle before calling random_bytes().","Use max(1, $length) if a minimum of one byte is always acceptable.","Fix the length computation that produces 0 or negative values.","Validate configuration-driven lengths at load time so zero never reaches the call site."],"exampleFix":"// before\n$bytes = random_bytes($config['key_length']);\n// after\n$length = (int) $config['key_length'];\nif ($length < 1) {\n    throw new InvalidArgumentException('key_length must be >= 1');\n}\n$bytes = random_bytes($length);","handlingStrategy":"validation","validationCode":"if (!is_int($length) || $length < 1) {\n    throw new InvalidArgumentException('length must be an integer >= 1');\n}","typeGuard":"null","tryCatchPattern":"try {\n    $bytes = random_bytes($length);\n} catch (Error $e) {\n    if (strpos($e->getMessage(), 'Length must be greater than 0') !== false) {\n        throw new InvalidArgumentException('length must be >= 1', 0, $e);\n    }\n    throw $e;\n}","preventionTips":["Validate lengths at configuration load time, not at call time.","Guard computed lengths (strlen differences, subtraction) against zero.","Use max(1, $length) only when a one-byte minimum is semantically fine.","Write unit tests covering length=0 and negative inputs."],"tags":["php","argument-out-of-range","randomness","validation"],"backgroundTag":"argument-out-of-range","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"}