search
HomeBackend DevelopmentPHP TutorialRandomness in PHP Do you consider yourself lucky? _php tips

This article analyzes issues related to generating random numbers for encryption. PHP 5 did not provide a simple mechanism to generate cryptographically strong random numbers, but PHP 7 solved this problem by introducing several CSPRNG functions.

1. What is CSPRNG

Quoting Wikipedia, a cryptographically secure pseudo-random number generator (CSPRNG) is a pseudo-random number generator (PRNG) that generates pseudo-random numbers suitable for cryptographic algorithms.

CSPRNG may be mainly used for:

  • Key generation (e.g., generate complex keys)
  • Generate random passwords for new users
  • Encryption system

A key aspect to achieving high levels of security is high-quality randomness

2. CSPRNG in PHP7

PHP 7 introduces two new functions that can be used to implement CSPRNG: random_bytes and random_int.

The random_bytes function returns a string and accepts an int input parameter representing the number of bytes of the returned result.

Example:

$bytes = random_bytes('10');
var_dump(bin2hex($bytes));
//possible ouput: string(20) "7dfab0af960d359388e6"

The random_int function returns an int number within the specified range.

Example:

var_dump(random_int(1, 100));
//possible output: 27

3. Background operating environment

The randomness of the above functions varies depending on the environment:

  • On windows, CryptGenRandom() is always used.
  • On other platforms, arc4random_buf() will be used if available (established on BSD series or systems with libbsd)
  • If none of the above is true, a Linux system call getrandom(2) will be used.
  • If still not possible, /dev/urandom will be used as the last available tool
  • If none of the above works, the system will throw an error

4. A simple test

A good random number generation system ensures appropriate generation "quality". To check this quality, a series of statistical tests are usually performed. Without delving into complex statistics topics, comparing a known behavior to the results of a number generator can help with quality assessment.

A simple test is the dice game. Assume that the probability of rolling 1 dice once and getting a result of 6 is 1/6, then if I roll 3 dice at the same time 100 times, the result will be roughly as follows:

0 6 = 57.9 times
1 6 = 34.7 times
2 sixes = 6.9 times
3 6s = 0.5 times
Here is the code to roll the dice 1,000,000 times:

$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);

Using PHP7’s random_int and simple rand function, you may get the following results

If we see rand and random_int first for a better comparison we can apply a formula and plot the result on a graph. The formula is: (php result-expected result)/expected result raised to the 0.5 power.

The results are as follows:

(Values ​​close to 0 are better)

Although 3 sixes does not perform well and this test is too simple for practical applications we can still see that random_int performs better than rand.

Furthermore, the security level of our application is increased due to the unpredictability and repeatable behavior of the random number generator.

What about PHP5

By default, PHP5 does not provide a strong random number generator. In fact, there are still options such as openssl_random_pseudo_bytes(), mcrypt_create_iv() or directly using the fread() function to use the /dev/random or /dev/urandom device. There are also packages such as RandomLib or libsodium.

If you want to start using a better random number generator and are ready to use PHP7 at the same time, you can use the Paragon Initiative Enterprises random_compat library. The random_compat library allows you to use random_bytes() and random_int()

in PHP 5.x projects.

This library can be installed via Composer:

composer require paragonie/random_compat
require '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 library and PHP7 use different order:

fread() /dev/urandom if available
mcrypt_create_iv($bytes, MCRYPT_CREATE_IV)
COM('CAPICOM.Utilities.1')->GetRandom()
openssl_random_pseudo_bytes()

A simple application of this library to generate passwords:

$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

Summary

You should always use a cryptographically secure pseudo-random number generator, the random_compat library provides a good implementation.

If you want to use a reliable source of random data, as you have seen in this article, it is recommended to use random_int and random_bytes as soon as possible.

The above is the relevant content about the randomness of PHP. I hope it will be helpful to everyone's learning.

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
Optimize PHP Code: Reducing Memory Usage & Execution TimeOptimize PHP Code: Reducing Memory Usage & Execution TimeMay 10, 2025 am 12:04 AM

TooptimizePHPcodeforreducedmemoryusageandexecutiontime,followthesesteps:1)Usereferencesinsteadofcopyinglargedatastructurestoreducememoryconsumption.2)LeveragePHP'sbuilt-infunctionslikearray_mapforfasterexecution.3)Implementcachingmechanisms,suchasAPC

PHP Email: Step-by-Step Sending GuidePHP Email: Step-by-Step Sending GuideMay 09, 2025 am 12:14 AM

PHPisusedforsendingemailsduetoitsintegrationwithservermailservicesandexternalSMTPproviders,automatingnotificationsandmarketingcampaigns.1)SetupyourPHPenvironmentwithawebserverandPHP,ensuringthemailfunctionisenabled.2)UseabasicscriptwithPHP'smailfunct

How to Send Email via PHP: Examples & CodeHow to Send Email via PHP: Examples & CodeMay 09, 2025 am 12:13 AM

The best way to send emails is to use the PHPMailer library. 1) Using the mail() function is simple but unreliable, which may cause emails to enter spam or cannot be delivered. 2) PHPMailer provides better control and reliability, and supports HTML mail, attachments and SMTP authentication. 3) Make sure SMTP settings are configured correctly and encryption (such as STARTTLS or SSL/TLS) is used to enhance security. 4) For large amounts of emails, consider using a mail queue system to optimize performance.

Advanced PHP Email: Custom Headers & FeaturesAdvanced PHP Email: Custom Headers & FeaturesMay 09, 2025 am 12:13 AM

CustomheadersandadvancedfeaturesinPHPemailenhancefunctionalityandreliability.1)Customheadersaddmetadatafortrackingandcategorization.2)HTMLemailsallowformattingandinteractivity.3)AttachmentscanbesentusinglibrarieslikePHPMailer.4)SMTPauthenticationimpr

Guide to Sending Emails with PHP & SMTPGuide to Sending Emails with PHP & SMTPMay 09, 2025 am 12:06 AM

Sending mail using PHP and SMTP can be achieved through the PHPMailer library. 1) Install and configure PHPMailer, 2) Set SMTP server details, 3) Define the email content, 4) Send emails and handle errors. Use this method to ensure the reliability and security of emails.

What is the best way to send an email using PHP?What is the best way to send an email using PHP?May 08, 2025 am 12:21 AM

ThebestapproachforsendingemailsinPHPisusingthePHPMailerlibraryduetoitsreliability,featurerichness,andeaseofuse.PHPMailersupportsSMTP,providesdetailederrorhandling,allowssendingHTMLandplaintextemails,supportsattachments,andenhancessecurity.Foroptimalu

Best Practices for Dependency Injection in PHPBest Practices for Dependency Injection in PHPMay 08, 2025 am 12:21 AM

The reason for using Dependency Injection (DI) is that it promotes loose coupling, testability, and maintainability of the code. 1) Use constructor to inject dependencies, 2) Avoid using service locators, 3) Use dependency injection containers to manage dependencies, 4) Improve testability through injecting dependencies, 5) Avoid over-injection dependencies, 6) Consider the impact of DI on performance.

PHP performance tuning tips and tricksPHP performance tuning tips and tricksMay 08, 2025 am 12:20 AM

PHPperformancetuningiscrucialbecauseitenhancesspeedandefficiency,whicharevitalforwebapplications.1)CachingwithAPCureducesdatabaseloadandimprovesresponsetimes.2)Optimizingdatabasequeriesbyselectingnecessarycolumnsandusingindexingspeedsupdataretrieval.

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 Tools

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.