
一、什么是CSPRNG
引用维基百科,一个密码学上安全的伪随机数发生器(Cryptographically Secure Pseudorandom Number Generator 缩写CSPRNG)是一个伪随机数生成器(PRNG),其生成的伪随机数适用于密码学算法。
CSPRNG可能主要用于:
$bytes = random_bytes("10");var_dump(bin2hex($bytes));//possible ouput: string(20) "7dfab0af960d359388e6"random_int 函数返回一个指定范围内的int型数字。
var_dump(random_int(1, 100));//possible output: 27三、后台运行环境
$times = 1000000;$result = [];for ($i=0; $i<$times; $i++){$dieRoll = array(6 => 0); //initializes just the six counting to zero$dieRoll[roll()] += 1; //first die$dieRoll[roll()] += 1; //second die$dieRoll[roll()] += 1; //third die$result[$dieRoll[6]] += 1; //counts the sixes}function roll(){return random_int(1,6);}var_dump($result);用PHP7 的 random_int 和简单的 rand 函数可能得到如下结果
如果先看到rand 和 random_int 更好的比较我们可以应用一个公式把结果画在图上。公式是:(php结果-期待的结果)/期待结果的0.5次方。
结果图如下:

(接近0的值更好)
尽管3个6的结果表现不好,并且这个测试对实际应用来说太过简单我们仍可以看出 random_int 表现优于 rand.
进一步,我们的应用的安全级别由于不可预测性和随机数发生器的可重复行为而得到提升。
PHP5 呢
缺省情况下,PHP5 不提供强壮的随机数发生器。实际上,还是有选择的比如 openssl_random_pseudo_bytes(), mcrypt_create_iv() 或者直接使用fread()函数来使用 /dev/random 或 /dev/urandom 设备。也有一些包比如 RandomLib 或 libsodium.
如果你想要开始使用一个更好的随机数发生器并且同时准备好使用PHP7,你可以使用Paragon Initiative Enterprises random_compat 库。 random_compat 库允许你在 PHP 5.x project.使用 random_bytes() and random_int()
这个库可以通过Composer安装:
composer require paragonie/random_compatrequire "vendor/autoload.php";$string = random_bytes(32);var_dump(bin2hex($string));// string(64) "8757a27ce421b3b9363b7825104f8bc8cf27c4c3036573e5f0d4a91ad2aaec6f"$int = random_int(0,255);var_dump($int);// int(81)random_compat 库和PHP7使用不同的顺序:
fread() /dev/urandom if availablemcrypt_create_iv($bytes, MCRYPT_CREATE_IV)COM("CAPICOM.Utilities.1")->GetRandom()openssl_random_pseudo_bytes()这个库的一个简单应用用来产生密码:
$passwordChar = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";$passwordLength = 8;$max = strlen($passwordChar) - 1;$password = "";for ($i = 0; $i < $passwordLength; ++$i) {$password .= $passwordChar[random_int(0, $max)];}echo $password;//possible output: 7rgG8GHu总结