How to use /dev/urandom with PHP to get CS random

2019-02-15 19:24发布

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?

1条回答
啃猪蹄的小仙女
2楼-- · 2019-02-15 19:55

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 than PHP_INT_MAX. (Yes, it uses /dev/urandom.)

Demo: http://3v4l.org/VJGCb

查看更多
登录 后发表回答