tyl*_*erl 15 php random cryptography
我需要替换rand()使用加密强随机数生成器的PHP 函数.
该openssl_random_pseudo_bytes()函数使您可以访问强随机数生成器,但它将其数据作为字节字符串输出.相反,我需要一个介于0和X之间的整数.
我想关键是将输出openssl_random_pseudo_bytes()转换为整数,然后你就可以对它进行任何数学运算.我可以想到一些从字节串转换为整数的"蛮力"方式,但我希望有一些......优雅.
tyl*_*erl 12
使用提供的建议,我使用OpenSSL为rand()创建了一个替代品.我会把它包含在这里供后人使用.
在$迂腐选项给出了启动时的结果将不会被均匀分布在可能的范围内分布在无偏置的结果.
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;
}
Run Code Online (Sandbox Code Playgroud)
手册页openssl_random_pseudo_bytes()有一个我认为你想要的例子.您可以调用bin2hex()输出openssl_random_pseudo_bytes()转换为十六进制数,然后hexdec()在该值上转换为十进制数.
$rand_num = hexdec(bin2hex(openssl_random_pseudo_bytes($length, $strong)));
Run Code Online (Sandbox Code Playgroud)
此时,您可以做任何想要获得所需范围值的数学运算.您可能拥有的另一个(骗子)选项是运行系统命令以生成随机数 - 对于可在线使用的各种操作系统,随机数生成器有一些不错的选项.
| 归档时间: |
|
| 查看次数: |
7965 次 |
| 最近记录: |