>本文研究了在密码学中使用随机数生成的挑战,强调了PHP 5和PHP 7之间的差异。PHP5缺少可用的机制来生成密码固定的随机数,而PHP 7则引入random_bytes
和random_int
了解csprngs
>密码固定的伪数字生成器(CSPRNG)是专为加密应用设计的PRNG。 它的关键特征是高质量的随机性,至关重要:>
random_bytes
php 7提供random_int
(返回指定字节长度的字符串)和
random_bytes
示例:
<code class="language-php">$bytes = random_bytes(10); var_dump(bin2hex($bytes)); // Possible output: string(20) "7dfab0af960d359388e6"</code>
random_int
示例:
<code class="language-php">var_dump(random_int(1, 100)); // Possible output: 27</code>
这些功能根据操作系统使用各种随机性来源,优先考虑安全选项,例如CryptGenRandom
(Windows),arc4random_buf
(bsd),getrandom(2)
>(linux),最后/dev/urandom
作为后备。 如果找不到合适的来源,就会丢弃错误。
测试随机性
评估随机数发生器的质量涉及统计测试。一个简单的例子是模拟骰子卷。 可以将滚动三分骰子1,000,000次滚动结果的预期分布与random_int
>和标准rand
函数产生的实际结果进行比较。
一个代码示例(简化为简洁)和比较图(如下所示)表明,random_int
>表现出更接近预期值的分布,表明与rand
>
> php 5替代
,openssl_random_pseudo_bytes()
,或直接访问mcrypt_create_iv()
>或/dev/random
>。 诸如Randomlib或libsodium之类的图书馆提供其他解决方案。/dev/urandom
库random_compat
>
库提供了 一个简单的密码生成示例,使用
使用CSPRNG对于安全应用程序至关重要。 库为PHP 5提供了向后兼容的解决方案,而PHP 7的开发人员应直接利用 。 优先考虑可靠的随机数会显着增强应用程序安全性。random_compat
>和random_bytes
功能。 它可以通过作曲家(random_int
)安装,并以下内容使用:<code class="language-php">$bytes = random_bytes(10);
var_dump(bin2hex($bytes));
// Possible output: string(20) "7dfab0af960d359388e6"</code>
与php 7相比,该库优先考虑不同的随机性来源
/dev/urandom
:random_compat
<code class="language-php">var_dump(random_int(1, 100));
// Possible output: 27</code>
random_compat
random_bytes
进一步阅读random_int
确认
感谢Scott Arciszewski的同行评审协助。
Description
Link
Die Hard Test
https://www.php.cn/link/1852a2083dbe1c2ec33ab9366feb2862
Chi-square test with dice example
https://www.php.cn/link/fb6a253729096c1e92e43c26a6fdadc3
Kolmogorov-Smirnov Test
https://www.php.cn/link/030d13e49bb7d1add5ac5ea2e4a43231
Spectral Test
https://www.php.cn/link/6bbd80b04535d39be5e02dbfd8730469
RaBiGeTe test suite
https://www.php.cn/link/e626afbcdb83368b3491c0c473da19f1
Random Number Generation In PHP (2011)
https://www.php.cn/link/f7ff233e4ed3e6b13c5d5c7a9201e4ec
Testing RNG part 1 and 2
https://www.php.cn/link/a1c71b134d46d7f7ff00f488874a8d43, https://www.php.cn/link/2e3517ba49c2a7c999b9c8381185ae4e
以上是PHP中的随机性 - 您感到幸运吗?的详细内容。更多信息请关注PHP中文网其他相关文章!