首页 >后端开发 >php教程 >PHP中的随机性 - 您感到幸运吗?

PHP中的随机性 - 您感到幸运吗?

Christopher Nolan
Christopher Nolan原创
2025-02-16 11:34:09155浏览

>本文研究了在密码学中使用随机数生成的挑战,强调了PHP 5和PHP 7之间的差异。PHP5缺少可用的机制来生成密码固定的随机数,而PHP 7则引入random_bytes>>>>>>>>为此目的功能。random_int

Randomness in PHP - Do You Feel Lucky?

了解csprngs

>密码固定的伪数字生成器(CSPRNG)是专为加密应用设计的PRNG。 它的关键特征是高质量的随机性,至关重要:

>

    密钥生成
  • 随机密码创建
  • 加密算法
  • Php 7

random_bytesphp 7提供random_int(返回指定字节长度的字符串)和

(在给定范围内返回一个随机整数),以使用CSPRNG功能。

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>

相比,表明了较高的随机性。

Randomness in PHP - Do You Feel Lucky?

> php 5替代

openssl_random_pseudo_bytes(),或直接访问mcrypt_create_iv()>或/dev/random>。 诸如Randomlib或libsodium之类的图书馆提供其他解决方案。/dev/urandom

random_compat>

> php 5兼容性,Paragon Initiative Enterprises

库提供了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>

使用CSPRNG对于安全应用程序至关重要。 库为PHP 5提供了向后兼容的解决方案,而PHP 7的开发人员应直接利用

>和

。 优先考虑可靠的随机数会显着增强应用程序安全性。random_compat random_bytes进一步阅读random_int

确认

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
感谢Scott Arciszewski的同行评审协助。

以上是PHP中的随机性 - 您感到幸运吗?的详细内容。更多信息请关注PHP中文网其他相关文章!

声明:
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn