如何在PHP中使用/dev/urandom获得CS随机数 [英] How to use /dev/urandom with PHP to get CS random numbers

查看:182
本文介绍了如何在PHP中使用/dev/urandom获得CS随机数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要在0到10,000,000之间创建随机整数,而我将需要数百万个这样的数字.这些数字必须尽可能接近CSPRNG,以便(例如)某人可以阅读,因此,在200万这样的数字中,有100万这样的数字会使他们觉得不可行来计算其余的100万数字.

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.

经过研究,我得出的结论是,使用现有工具,使用/dev/urandom(Unix/PHP)将是我最好的选择.

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;
}

来源: https://codeascraft .com/2012/07/19/better-random-numbers-in-php-using-devurandom/

鉴于我需要创建大量随机数,我会更好地将/dev/urandom管道传输到文件,然后一次读取3个字节(2 ^ 24 = 1600万)并进行转换到整数?

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?

推荐答案

PHP 7推出时,它具有一个名为

When PHP 7 comes out, it has a new function called random_int() that serves this purpose.

如果您今天(例如在PHP 5项目中)需要此功能,请查看 random_compat .

If you need this today (i.e. in a PHP 5 project), check out random_compat.

至少,请查看 random_int()的实现方式在random_compat中.除其他原因外,它仍然适用于大于PHP_INT_MAX的范围. (是的,它使用/dev/urandom.)

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.)

演示: http://3v4l.org/VJGCb

这篇关于如何在PHP中使用/dev/urandom获得CS随机数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆