我需要替换 PHP 的 rand()
函数,该函数使用加密强度高的随机数生成器。
openssl_random_pseudo_bytes()
函数可让您访问强随机数生成器,但它会将其数据输出为字节字符串。相反,我需要一个介于 0 和 X 之间的整数。
我认为关键是将 openssl_random_pseudo_bytes()
的输出转换为整数,然后您可以根据需要对其进行任何数学运算。我可以想到一些从字节字符串转换为整数的“强力”方法,但我希望得到一些……优雅的东西。
最佳答案
根据提供的建议,我使用 OpenSSL 创建了 rand() 的替代品。我会把它包括在这里供后代使用。
$pedantic 选项通过在结果未均匀分布在可能范围内时重新开始来提供无偏差结果。
function crypto_rand($min,$max,$pedantic=True) {
$diff = $max - $min;
if ($diff <= 0) return $min; // not so random...
$range = $diff + 1; // because $max is inclusive
$bits = ceil(log(($range),2));
$bytes = ceil($bits/8.0);
$bits_max = 1 << $bits;
// e.g. if $range = 3000 (bin: 101110111000)
// +--------+--------+
// |....1011|10111000|
// +--------+--------+
// bits=12, bytes=2, bits_max=2^12=4096
$num = 0;
do {
$num = hexdec(bin2hex(openssl_random_pseudo_bytes($bytes))) % $bits_max;
if ($num >= $range) {
if ($pedantic) continue; // start over instead of accepting bias
// else
$num = $num % $range; // to hell with security
}
break;
} while (True); // because goto attracts velociraptors
return $num + $min;
}
关于php - 将 rand() 替换为 openssl_random_pseudo_bytes(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1313223/