I need to create random integers between the values of 0 and 10,000,000, and I will need several million such numbers. The numbers must be as close to a CSPRNG as possible in that should (for example) someone get to read, so 1 million out of 2 million such numbers that they would find it impracticable to work out the remaining 1 million numbers.
After some research I’ve come to the conclusion that with the tools I have available, (Unix/PHP) using /dev/urandom will be my best bet.
I came across this solution:
// equiv to rand, mt_rand
// returns int in *closed* interval [$min,$max]
function devurandom_rand($min = 0, $max = 0x7FFFFFFF) {
$diff = $max - $min;
if ($diff < 0 || $diff > 0x7FFFFFFF) {
throw new RuntimeException("Bad range");
}
$bytes = mcrypt_create_iv(4, MCRYPT_DEV_URANDOM);
if ($bytes === false || strlen($bytes) != 4) {
throw new RuntimeException("Unable to get 4 bytes");
}
$ary = unpack("Nint", $bytes);
$val = $ary['int'] & 0x7FFFFFFF; // 32-bit safe
$fp = (float) $val / 2147483647.0; // convert to [0,1]
return round($fp * $diff) + $min;
}
Source: https://codeascraft.com/2012/07/19/better-random-numbers-in-php-using-devurandom/
Given that I need to create a large amount of random numbers, would I be better piping /dev/urandom to a file(s), and then read 3 bytes (2^24 = 16 million) at a time and convert to integer?
Is either solution suitable for my needs?
When PHP 7 comes out, it has a new function called
random_int()
that serves this purpose.If you need this today (i.e. in a PHP 5 project), check out random_compat.
At the very least, look at how
random_int()
is implemented in random_compat. Among other reasons, it still works for ranges larger thanPHP_INT_MAX
. (Yes, it uses/dev/urandom
.)Demo: http://3v4l.org/VJGCb