Table of Contents
PHP中的随机性——你觉得自己幸运吗?
Home Backend Development PHP Tutorial PHP中的随机性——你觉得自己幸运吗?_PHP教程

PHP中的随机性——你觉得自己幸运吗?_PHP教程

Jul 12, 2016 am 09:00 AM
php randomness

PHP中的随机性——你觉得自己幸运吗?

本文分析了生成用于加密的随机数的相关问题。 PHP 5没有提供一种简单的机制来生成密码学上强壮的随机数,但是PHP 7通过引入几个CSPRNG函数来解决了这个问题。

Cryptography Randomness in PHP

什么是CSPRNG

引用维基百科,一个密码学上安全的伪随机数发生器Cryptographically Secure Pseudorandom Number Generator 缩写CSPRNG)是一个伪随机数生成器PRNG),其生成的伪随机数适用于密码学算法。

CSPRNG可能主要用于:

  • 密钥生成例如,生成复杂的密钥)

  • 为新用户产生随机的密码

  • 加密系统

获得高级别安全性的一个关键方面就是高品质的随机性

PHP7 中的CSPRNG

PHP 7引入了两个新函数可以用来实现CSPRNG: random_bytes 和 random_int。

random_bytes 函数返回一个字符串,接受一个int型入参代表返回结果的字节数。

例子:

<ol class="dp-j"><li class="alt"><span><span>$bytes = random_bytes(</span><span class="string">'10'</span><span>); </span></span></li><li><span>var_dump(bin2hex($bytes)); </span></li><li class="alt"><span><span class="comment">//possible ouput: string(20) "7dfab0af960d359388e6"</span><span> </span></span></li></ol>
Copy after login

random_int 函数返回一个指定范围内的int型数字。

例子:

<ol class="dp-j"><li class="alt"><span><span>var_dump(random_int(</span><span class="number">1</span><span>, </span><span class="number">100</span><span>)); </span></span></li><li><span><span class="comment">//possible output: 27</span><span> </span></span></li></ol>
Copy after login

后台运行环境

以上函数的随机性不同的取决于环境:

  • 在window上,CryptGenRandom()总是被使用。

  • 在其他平台,arc4random_buf()如果可用会被使用在BSD系列或者具有libbsd的系统上成立)

  • 以上都不成立的话,一个linux系统调用getrandom(2)会被使用。

  • 如果还不行,/dev/urandom 会被作为最后一个可使用的工具

  • 如果以上都不行,系统会抛出错误

一个简单的测试

一个好的随机数生成系统保证合适的产生“质量”。为了检查这个质量, 通常要执行一连串的统计测试。不需要深入研究复杂的统计主题,比较一个已知的行为和数字生成器的结果可以帮助质量评价。

一个简单的测试是骰子游戏。假设掷1个骰子1次得到结果为6的概率是1/6,那么如果我同时掷3个骰子100次,得到的结果粗略如下:

  • 0 个6 = 57.9 次

  • 1 个6 = 34.7次

  • 2 个6 = 6.9次

  • 3 个6 = 0.5次

以下是是实现实现掷骰子1,000,000次的代码:

<ol class="dp-j"><li class="alt"><span><span>$times = </span><span class="number">1000000</span><span>; </span></span></li><li><span>$result = []; </span></li><li class="alt"><span><span class="keyword">for</span><span> ($i=</span><span class="number">0</span><span>; $i<$times; $i++){ </span></span></li><li><span>    $dieRoll = array(<span class="number">6</span><span> => </span><span class="number">0</span><span>); </span><span class="comment">//initializes just the six counting to zero</span><span> </span></span></li><li class="alt"><span>    $dieRoll[roll()] += <span class="number">1</span><span>; </span><span class="comment">//first die</span><span> </span></span></li><li><span>    $dieRoll[roll()] += <span class="number">1</span><span>; </span><span class="comment">//second die</span><span> </span></span></li><li class="alt"><span>    $dieRoll[roll()] += <span class="number">1</span><span>; </span><span class="comment">//third die</span><span> </span></span></li><li><span>    $result[$dieRoll[<span class="number">6</span><span>]] += </span><span class="number">1</span><span>; </span><span class="comment">//counts the sixes</span><span> </span></span></li><li class="alt"><span>} </span></li><li><span>function roll(){ </span></li><li class="alt"><span>    <span class="keyword">return</span><span> random_int(</span><span class="number">1</span><span>,</span><span class="number">6</span><span>); </span></span></li><li><span>} </span></li><li class="alt"><span>var_dump($result); </span></li></ol>
Copy after login

用PHP7 的 random_int 和简单的 rand 函数可能得到如下结果

Sixes

expected

random_int

0

579000

579430

1

347000

346927

2

69000

68985

3

5000

4658

如果先看到rand 和 random_int 更好的比较我们可以应用一个公式把结果画在图上。公式是:(php结果-期待的结果)/期待结果的0.5次方。

结果图如下:

test random graph

接近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安装:

<ol class="dp-j"><li class="alt"><span><span>composer require paragonie/random_compat </span></span></li><li><span> </span></li><li class="alt"><span>require <span class="string">'vendor/autoload.php'</span><span>; </span></span></li><li><span>$string = random_bytes(<span class="number">32</span><span>); </span></span></li><li class="alt"><span>var_dump(bin2hex($string)); </span></li><li><span><span class="comment">// string(64) "8757a27ce421b3b9363b7825104f8bc8cf27c4c3036573e5f0d4a91ad2aaec6f"</span><span> </span></span></li><li class="alt"><span>$<span class="keyword">int</span><span> = random_int(</span><span class="number">0</span><span>,</span><span class="number">255</span><span>); </span></span></li><li><span>var_dump($<span class="keyword">int</span><span>); </span></span></li><li class="alt"><span><span class="comment">// int(81)</span><span> </span></span></li></ol>
Copy after login

random_compat 库和PHP7使用不同的顺序:

<ol class="dp-j"><li class="alt"><span><span>fread() /dev/urandom </span><span class="keyword">if</span><span> available </span></span></li><li><span>mcrypt_create_iv($bytes, MCRYPT_CREATE_IV) </span></li><li class="alt"><span>COM(<span class="string">'CAPICOM.Utilities.1'</span><span>)->GetRandom() </span></span></li><li><span>openssl_random_pseudo_bytes() </span></li></ol>
Copy after login

想知道为什么是这个顺序建议阅读 documentation.

这个库的一个简单应用用来产生密码:

<ol class="dp-j"><li class="alt"><span><span>$passwordChar = </span><span class="string">'0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'</span><span>; </span></span></li><li><span>$passwordLength = <span class="number">8</span><span>; </span></span></li><li class="alt"><span>$max = strlen($passwordChar) - <span class="number">1</span><span>; </span></span></li><li><span>$password = <span class="string">''</span><span>; </span></span></li><li class="alt"><span><span class="keyword">for</span><span> ($i = </span><span class="number">0</span><span>; $i < $passwordLength; ++$i) { </span></span></li><li><span>    $password .= $passwordChar[random_int(<span class="number">0</span><span>, $max)]; </span></span></li><li class="alt"><span>} </span></li><li><span>echo $password; </span></li><li class="alt"><span><span class="comment">//possible output: 7rgG8GHu</span><span> </span></span></li></ol>
Copy after login

总结

你总是应该使用一个密码学上安全的伪随机数生成器,random_compat 库提供了一种好的实现。

如果你想要使用可靠的随机数据源,如你在本文所见,建议尽快使用 random_int 和 random_bytes.

译文链接:http://www.codeceo.com/article/php-random.html
英文原文:Randomness in PHP – Do You Feel Lucky?

www.bkjia.comtruehttp://www.bkjia.com/PHPjc/1093808.htmlTechArticlePHP中的随机性——你觉得自己幸运吗? 本文分析了生成用于加密的随机数的相关问题。PHP5没有提供一种简单的机制来生成密码学上强壮的...
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Roblox: Bubble Gum Simulator Infinity - How To Get And Use Royal Keys
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Nordhold: Fusion System, Explained
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Mandragora: Whispers Of The Witch Tree - How To Unlock The Grappling Hook
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1666
14
PHP Tutorial
1273
29
C# Tutorial
1253
24
PHP and Python: Comparing Two Popular Programming Languages PHP and Python: Comparing Two Popular Programming Languages Apr 14, 2025 am 12:13 AM

PHP and Python each have their own advantages, and choose according to project requirements. 1.PHP is suitable for web development, especially for rapid development and maintenance of websites. 2. Python is suitable for data science, machine learning and artificial intelligence, with concise syntax and suitable for beginners.

PHP: A Key Language for Web Development PHP: A Key Language for Web Development Apr 13, 2025 am 12:08 AM

PHP is a scripting language widely used on the server side, especially suitable for web development. 1.PHP can embed HTML, process HTTP requests and responses, and supports a variety of databases. 2.PHP is used to generate dynamic web content, process form data, access databases, etc., with strong community support and open source resources. 3. PHP is an interpreted language, and the execution process includes lexical analysis, grammatical analysis, compilation and execution. 4.PHP can be combined with MySQL for advanced applications such as user registration systems. 5. When debugging PHP, you can use functions such as error_reporting() and var_dump(). 6. Optimize PHP code to use caching mechanisms, optimize database queries and use built-in functions. 7

PHP in Action: Real-World Examples and Applications PHP in Action: Real-World Examples and Applications Apr 14, 2025 am 12:19 AM

PHP is widely used in e-commerce, content management systems and API development. 1) E-commerce: used for shopping cart function and payment processing. 2) Content management system: used for dynamic content generation and user management. 3) API development: used for RESTful API development and API security. Through performance optimization and best practices, the efficiency and maintainability of PHP applications are improved.

PHP vs. Python: Understanding the Differences PHP vs. Python: Understanding the Differences Apr 11, 2025 am 12:15 AM

PHP and Python each have their own advantages, and the choice should be based on project requirements. 1.PHP is suitable for web development, with simple syntax and high execution efficiency. 2. Python is suitable for data science and machine learning, with concise syntax and rich libraries.

The Enduring Relevance of PHP: Is It Still Alive? The Enduring Relevance of PHP: Is It Still Alive? Apr 14, 2025 am 12:12 AM

PHP is still dynamic and still occupies an important position in the field of modern programming. 1) PHP's simplicity and powerful community support make it widely used in web development; 2) Its flexibility and stability make it outstanding in handling web forms, database operations and file processing; 3) PHP is constantly evolving and optimizing, suitable for beginners and experienced developers.

PHP and Python: Code Examples and Comparison PHP and Python: Code Examples and Comparison Apr 15, 2025 am 12:07 AM

PHP and Python have their own advantages and disadvantages, and the choice depends on project needs and personal preferences. 1.PHP is suitable for rapid development and maintenance of large-scale web applications. 2. Python dominates the field of data science and machine learning.

PHP vs. Other Languages: A Comparison PHP vs. Other Languages: A Comparison Apr 13, 2025 am 12:19 AM

PHP is suitable for web development, especially in rapid development and processing dynamic content, but is not good at data science and enterprise-level applications. Compared with Python, PHP has more advantages in web development, but is not as good as Python in the field of data science; compared with Java, PHP performs worse in enterprise-level applications, but is more flexible in web development; compared with JavaScript, PHP is more concise in back-end development, but is not as good as JavaScript in front-end development.

PHP and Python: Different Paradigms Explained PHP and Python: Different Paradigms Explained Apr 18, 2025 am 12:26 AM

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

See all articles