paragonie/random_compat · critical · Exception

Could not gather sufficient random data

Error message

Could not gather sufficient random data

What it means

The mcrypt-backed random_bytes() throws this Exception when mcrypt_create_iv(MCRYPT_DEV_URANDOM) returns false or otherwise fails to deliver random bytes, meaning even the urandom-backed mcrypt path is unusable. The polyfill fails closed rather than return weak randomness.

Solutions

  1. Verify the mcrypt extension is installed and enabled (php -m | grep mcrypt).
  2. Ensure /dev/urandom exists and is readable by the PHP process.
  3. Upgrade to PHP 7.0+ where random_bytes() is native and mcrypt is not needed.
  4. Remove mcrypt from disable_functions / relax open_basedir if it blocks urandom.
  5. Fail and alert rather than falling back to rand()/mt_rand(), which are not cryptographically secure.

Example fix

// before
$token = bin2hex(random_bytes(32));
// after
try {
    $token = bin2hex(random_bytes(32));
} catch (Exception $e) {
    throw new RuntimeException('Secure RNG unavailable; cannot mint token', 0, $e);
}
Defensive patterns

Strategy: try-catch

Validate before calling

// Pre-check backend availability:
// if (!extension_loaded('mcrypt') && PHP_VERSION_ID < 70000) failHard('No RNG backend');

Type guard

null

Try / catch

try {
    $token = random_bytes(32);
} catch (Exception $e) {
    // Do NOT degrade to rand()/mt_rand()/uniqid()
    throw new RuntimeException('CSPRNG unavailable; token generation aborted', 0, $e);
}

Prevention

When it happens

Trigger: random_bytes() called on a PHP 5 system where mcrypt_create_iv() fails — mcrypt unavailable, /dev/urandom unreadable, or the function suppressed by disable_functions — reaching the throw at lib/random_bytes_mcrypt.php:75.

Common situations: Legacy PHP 5.x builds without mcrypt compiled in, containers missing /dev/urandom, chroot jails lacking device nodes, or hosts that disable mcrypt functions via disable_functions.

Understand the failure class

Background: "unsupported platform" / "not supported on this platform" errors: what they mean and how to fix them — this error's family across 47 libraries.

Related errors


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

Appendix: source

Thrown at lib/random_bytes_mcrypt.php:75

        }

        /** @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;
        }

        /**
         * If we reach here, PHP has failed us.
         */
        throw new Exception(
            'Could not gather sufficient random data'
        );
    }
}

View on GitHub (pinned to b5d188cc9d)