{"record":{"id":"d05b5a6c8847724e","repo":"paragonie/random_compat","slug":"length-must-be-greater-than-0","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_com_dotnet.php","lineNumber":53,"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        /** @var string $buf */\n        $buf = '';\n        if (!class_exists('COM')) {\n            throw new Error(\n                'COM does not exist'\n            );\n        }\n        /** @var COM $util */\n        $util = new COM('CAPICOM.Utilities.1');\n        $execCount = 0;\n\n        /**\n         * Let's not let it loop forever. If we run N times and fail to\n         * get N bytes of random data, then CAPICOM has failed us.","sourceCodeStart":35,"sourceCodeEnd":71,"githubUrl":"https://github.com/paragonie/random_compat/blob/b5d188cc9d5e02f94d2c41da23093f1ef557c5b1/lib/random_bytes_com_dotnet.php#L35-L71","documentation":"random_bytes() is specified to return cryptographically secure random bytes for a requested length; a length below 1 is meaningless. The library explicitly throws Error when $bytes < 1, matching native PHP 7 behavior where a non-positive length raises ValueError/TypeError. It exists to fail fast rather than return an empty, insecure string.","triggerScenarios":"Calling random_bytes(0), random_bytes(-5), or any computed length that evaluates to <= 0 (e.g. subtracting from a counter, an empty/zero config value, intval of '0').","commonSituations":"A config option for token/key length defaults to 0 or is unset; loop code that computes remaining bytes as 0 and still calls random_bytes; users migrating code that previously tolerated '' from custom RNG helpers.","solutions":["Guard the length before calling: if ($len < 1) { throw new InvalidArgumentException('length must be >= 1'); }","Fix the source of the zero/negative value (config default, arithmetic, subtraction).","Return early or skip generation when the requested size is legitimately zero.","For variable lengths, clamp: $len = max(1, $len); if the domain guarantees at least 1 byte is needed."],"exampleFix":"// before\n$key = random_bytes($config['key_length']);\n// after\n$len = (int) ($config['key_length'] ?? 32);\nif ($len < 1) {\n    throw new InvalidArgumentException('key_length must be >= 1');\n}\n$key = random_bytes($len);","handlingStrategy":"validation","validationCode":"if (!is_int($len) || $len < 1) {\n    throw new InvalidArgumentException('length must be >= 1');\n}\n$bytes = random_bytes($len);","typeGuard":"function isPositiveInt($v) {\n    return is_int($v) && $v >= 1;\n}","tryCatchPattern":"try {\n    $bytes = random_bytes($len);\n} catch (Error $e) {\n    if ($e->getMessage() === 'Length must be greater than 0') {\n        throw new InvalidArgumentException('key length must be positive', 0, $e);\n    }\n    throw $e;\n}","preventionTips":["Validate configured lengths at startup (fail fast on bad config defaults).","Use max(1, $len) only when the domain guarantees at least 1 byte is needed; otherwise reject explicitly.","Beware arithmetic that can yield 0 or negatives (subtraction of counters, empty inputs).","Prefer named constants for standard sizes (16/32 bytes) over computed values."],"tags":["php","argument-out-of-range","random-bytes","validation"],"backgroundTag":"value-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"}