paragonie/random_compat · error · Error

Length must be greater than 0

Error message

Length must be greater than 0

What it means

The mcrypt-backed random_bytes() rejects integer arguments less than 1 with this Error, because generating zero or negative random bytes is meaningless. It mirrors PHP 7's built-in random_bytes() behavior for the polyfill.

Solutions

  1. Validate before calling: reject lengths < 1 with a clear domain error.
  2. Clamp with max(1, $length) when one byte minimum is acceptable.
  3. Correct the upstream calculation that yields a non-positive length.
  4. Enforce positive integer lengths at configuration load time.

Example fix

// before
$nonce = random_bytes($opts['nonce_len'] ?? 0);
// after
$len = (int) ($opts['nonce_len'] ?? 24);
if ($len < 1) {
    $len = 24;
}
$nonce = random_bytes($len);
Defensive patterns

Strategy: validation

Validate before calling

$size = (int) $rawSize;
if ($size < 1) {
    throw new InvalidArgumentException('size must be >= 1');
}

Type guard

null

Try / catch

try {
    $buf = random_bytes($size);
} catch (Error $e) {
    throw new InvalidArgumentException('random_bytes() requires a length >= 1', 0, $e);
}

Prevention

When it happens

Trigger: Calling random_bytes(0), random_bytes(-8), or a value that casts to <= 0 (e.g. null cast, 0.4 cast via the earlier intval step) on the mcrypt backend — the '$bytes < 1' check at lib/random_bytes_mcrypt.php:54 fires.

Common situations: Zero-length salt/IV requests from misconfigured lengths, off-by-one computations like strlen($x) - strlen($x), or defaults of 0 in config arrays.

Related errors


AI-assisted analysis of paragonie/random_compat@b5d188cc9d (2026-09-13). Data as JSON: /api/errors/97ab705b4e466cb5. Report an issue: GitHub.

Appendix: source

Thrown at lib/random_bytes_mcrypt.php:54

     * @param int $bytes
     *
     * @throws Exception
     *
     * @return string
     */
    function random_bytes($bytes)
    {
        try {
            /** @var int $bytes */
            $bytes = RandomCompat_intval($bytes);
        } catch (TypeError $ex) {
            throw new TypeError(
                'random_bytes(): $bytes must be an integer'
            );
        }

        if ($bytes < 1) {
            throw new Error(
                'Length must be greater than 0'
            );
        }

        /** @var string|bool $buf */
        $buf = @mcrypt_create_iv((int) $bytes, (int) MCRYPT_DEV_URANDOM);
        if (
            is_string($buf)
                &&
            RandomCompat_strlen($buf) === $bytes
        ) {
            /**
             * Return our random entropy buffer here:
             */
            return $buf;
        }

        /**

View on GitHub (pinned to b5d188cc9d)