search
HomeBackend DevelopmentPHP TutorialPHP中的随机性——你觉得自己幸运吗?_PHP教程

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>

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>

后台运行环境

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

  • 在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>

用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>

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>

想知道为什么是这个顺序建议阅读 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>

总结

你总是应该使用一个密码学上安全的伪随机数生成器,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
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
PHP Dependency Injection Container: A Quick StartPHP Dependency Injection Container: A Quick StartMay 13, 2025 am 12:11 AM

APHPDependencyInjectionContainerisatoolthatmanagesclassdependencies,enhancingcodemodularity,testability,andmaintainability.Itactsasacentralhubforcreatingandinjectingdependencies,thusreducingtightcouplingandeasingunittesting.

Dependency Injection vs. Service Locator in PHPDependency Injection vs. Service Locator in PHPMay 13, 2025 am 12:10 AM

Select DependencyInjection (DI) for large applications, ServiceLocator is suitable for small projects or prototypes. 1) DI improves the testability and modularity of the code through constructor injection. 2) ServiceLocator obtains services through center registration, which is convenient but may lead to an increase in code coupling.

PHP performance optimization strategies.PHP performance optimization strategies.May 13, 2025 am 12:06 AM

PHPapplicationscanbeoptimizedforspeedandefficiencyby:1)enablingopcacheinphp.ini,2)usingpreparedstatementswithPDOfordatabasequeries,3)replacingloopswitharray_filterandarray_mapfordataprocessing,4)configuringNginxasareverseproxy,5)implementingcachingwi

PHP Email Validation: Ensuring Emails Are Sent CorrectlyPHP Email Validation: Ensuring Emails Are Sent CorrectlyMay 13, 2025 am 12:06 AM

PHPemailvalidationinvolvesthreesteps:1)Formatvalidationusingregularexpressionstochecktheemailformat;2)DNSvalidationtoensurethedomainhasavalidMXrecord;3)SMTPvalidation,themostthoroughmethod,whichchecksifthemailboxexistsbyconnectingtotheSMTPserver.Impl

How to make PHP applications fasterHow to make PHP applications fasterMay 12, 2025 am 12:12 AM

TomakePHPapplicationsfaster,followthesesteps:1)UseOpcodeCachinglikeOPcachetostoreprecompiledscriptbytecode.2)MinimizeDatabaseQueriesbyusingquerycachingandefficientindexing.3)LeveragePHP7 Featuresforbettercodeefficiency.4)ImplementCachingStrategiessuc

PHP Performance Optimization Checklist: Improve Speed NowPHP Performance Optimization Checklist: Improve Speed NowMay 12, 2025 am 12:07 AM

ToimprovePHPapplicationspeed,followthesesteps:1)EnableopcodecachingwithAPCutoreducescriptexecutiontime.2)ImplementdatabasequerycachingusingPDOtominimizedatabasehits.3)UseHTTP/2tomultiplexrequestsandreduceconnectionoverhead.4)Limitsessionusagebyclosin

PHP Dependency Injection: Improve Code TestabilityPHP Dependency Injection: Improve Code TestabilityMay 12, 2025 am 12:03 AM

Dependency injection (DI) significantly improves the testability of PHP code by explicitly transitive dependencies. 1) DI decoupling classes and specific implementations make testing and maintenance more flexible. 2) Among the three types, the constructor injects explicit expression dependencies to keep the state consistent. 3) Use DI containers to manage complex dependencies to improve code quality and development efficiency.

PHP Performance Optimization: Database Query OptimizationPHP Performance Optimization: Database Query OptimizationMay 12, 2025 am 12:02 AM

DatabasequeryoptimizationinPHPinvolvesseveralstrategiestoenhanceperformance.1)Selectonlynecessarycolumnstoreducedatatransfer.2)Useindexingtospeedupdataretrieval.3)Implementquerycachingtostoreresultsoffrequentqueries.4)Utilizepreparedstatementsforeffi

See all articles

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

Hot Tools

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.