嗨,我找到了这个脚本。
脚本:
function urandom_rand($min = 0, $max = 0x7FFFFFFF){
$min = (int)$min;
$max = (int)$max;
if ($max <= $min)
trigger_error('Minimum value must be greater than maximum value.');
if ($min < 0 || $max > 0x7FFFFFFF)
trigger_error('Values must be between 0 and 2147483647.');
$M = bcadd(0x7FFFFFFF,1); // (up bound of iv)+1
$N = bcadd($max-$min, 1); // how many different values this function can return
$h = bcmod($M, $N); // the last h integers from unpack are "invalids"
do{
$bytes = mcrypt_create_iv(4, MCRYPT_DEV_URANDOM);
$r = unpack("N", $bytes)[1] & 0x7FFFFFFF;
} while ($r > ($M-$h));
return (bcmod($r, $N) + $min);
}
我的问题是:这个脚本是生成随机数的好解决方案吗?
这个函数可能有效,但不要重新发明轮子。
为什么不使用PHP内置的int rand(int$min,int$max)或int mt_rand(int$min-int$max)函数呢?
主要的区别是mt_rand更快,sudo随机数不那么容易预测。
如果您需要加密随机性,建议在php7中使用int random_int(int$min,int$max)。在较旧的php版本上,使用openssl_random_pseudo_bytes,并检查crypto_strong参数以验证生成的数字在加密方面是否强大。