Home  >  Article  >  Backend Development  >  Randomness in PHP Do you consider yourself lucky? , PHP randomness feeling_PHP tutorial

Randomness in PHP Do you consider yourself lucky? , PHP randomness feeling_PHP tutorial

WBOY
WBOYOriginal
2016-07-12 09:00:13735browse

Randomness in PHP Do you think you are lucky? , PHP randomness feels

This article analyzes the 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 aid in 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 the 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.

Articles you may be interested in:

  • PHP code to generate random numbers or strings
  • PHP n unique random number generation code
  • PHP dynamically randomly generates verification code code
  • A super easy-to-use PHP image upload class (random name, thumbnail, watermark)
  • php array function sequence shuffle() and array_rand( ) Introduction to the use of random functions
  • Examples of PHP probability algorithms suitable for lottery programs and random advertisements
  • php uses the array_rand() function to randomly select one or more elements from an array
  • Three methods for php to generate random numbers
  • A summary of methods for PHP to generate non-repeating random numbers
  • How to randomly generate a combination of numbers and letters in php

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/1094754.htmlTechArticleRandomness in PHP Do you think you are lucky? , PHP Randomness Feeling This article analyzes the issues related to generating random numbers for encryption. PHP 5 does not provide a simple mechanism to generate passwords...
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