<?php
if (!function_exists('random_bytes')) {
function random_bytes($size)
{
if(!is_int($size))
throw new InvalidArgumentException('random_bytes: $size must be an int');
if($size < 0)
throw new InvalidArgumentException('random_bytes: $size must not be negative');
//if(function_exists('mcrypt_create_iv'))
//{
// $result = mcrypt_create_iv($size, MCRYPT_DEV_URANDOM);
//}
else if(function_exists('openssl_random_pseudo_bytes'))
{
$result = openssl_random_pseudo_bytes($size, $isSecure);
if($isSecure !== true)
{
throw new RuntimeException("random_bytes: openssl_random_pseudo_bytes returned insecure data");
}
}
else
{
throw new RuntimeException("random_bytes: No RNG found");
}
if(!is_string($result) || (strlen($result) !== $size))
{
throw new RuntimeException("random_bytes: RNG is unavailable or broken");
}
return $result;
}
}
if (!function_exists('random_int')) {
function random_int($min, $max)
{
if(!defined('PHP_INT_SIZE'))
trigger_error("random_int: This version of PHP is not supported", E_USER_ERROR);
if(!is_int($min))
throw new InvalidArgumentException('random_int: $min must be an int');
if(!is_int($min))
throw new InvalidArgumentException('random_int: $min must be an int');
if($min > $max)
throw new InvalidArgumentException('random_int: $min must be less or equal to $max');
$range = $max - $min + 1;
// the rejection probability is at most 0.5, so this corresponds to a failure probability of 2^-128 for a working RNG
for($attempts = 0; $attempts < 128; $attempts++)
{
// generate a random integer
$bytes = random_bytes(PHP_INT_SIZE);
$value = 0;
for($i = 0; $i < PHP_INT_SIZE; $i++)
{
$value = ($value << 8) | ord($bytes[$i]);
}
if(!is_int($range))
{
if(($value >= $min) && ($value <= $max))
{
return $value;
}
} else {
$value &= PHP_INT_MAX;
// equivalent to (PHP_INT_MAX + 1) % range, but avoids int overflows
// I'm assuming PHP_INT_MAX + 1 is a power-of-two
$reject = (-$range & PHP_INT_MAX) % $range;
if($value >= $reject)
{
return ($value % $range) + $min;
}
}
}
throw new RuntimeException("random_int: RNG is broken - too many rejections");
}
}
random_int(0, 1000);
Fatal error: Uncaught exception 'RuntimeException' with message 'random_bytes: No RNG found' in /in/s2cvp:25
Stack trace:
#0 /in/s2cvp(53): random_bytes(8)
#1 /in/s2cvp(81): random_int(0, 1000)
#2 {main}
thrown in /in/s2cvp on line 25
Process exited with code 255.
Output for 5.0.5
Fatal error: Class 'RuntimeException' not found in /in/s2cvp on line 25
Process exited with code 255.
Output for 5.0.0 - 5.0.4
Fatal error: random_int: This version of PHP is not supported in /in/s2cvp on line 40
Process exited with code 255.
Output for 4.4.2 - 4.4.9
Parse error: syntax error, unexpected T_NEW in /in/s2cvp on line 7
Process exited with code 255.