The randomness in PHP-do you feel lucky?

Source: Internet
Author: User
Tags cryptographically secure
Original link: http://www.sitepoint.com/ocr-in-php-read-text-from-images-with-tesseract/

This article is starting in the code farm: http://www.codeceo.com/article/php-ocr-tesseract-get-text.html

Translator: Chu Kang (Weibo: Chu Kang Singasong)

This paper analyzes the problems related to generating random numbers for encryption. PHP 5 does not provide a simple mechanism to generate cryptographic strong random numbers, but PHP 7 solves this problem by introducing several CSPRNG functions.

What is CSPRNG

Referring to Wikipedia, a cryptographic safe pseudo-random number generator (cryptographically secure pseudorandom number Generator abbreviation CSPRNG) is a pseudo-random numbers generator (PRNG), Its generated pseudo-random number is applicable to cryptography algorithms.

CSPRNG may be used primarily for:

    1. Key generation (for example, generating complex keys)

    2. Generate a random password for a new user

    3. Encryption system

A key aspect of getting high-level security is high-quality randomness

The 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 that accepts an int type parameter that represents the number of bytes that returned the result.

Example:

$bytes = Random_bytes (' ten '); Var_dump (Bin2Hex ($bytes));//possible ouput:string ("7dfab0af960d359388e6")

The Random_int function returns a number of type int within a specified range.

Example:

Var_dump (Random_int (1));//possible output:27

Background run environment

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

    • On the window, 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 not,/dev/urandom will be used as the last available tool.

    • If none of the above, the system throws an error

A simple test

A good random number generation system guarantees the proper production of "quality". In order to check this quality, a series of statistical tests are usually performed. There is no need to delve into complex statistical topics and compare the results of a known behavior and number generator to help with quality evaluation.

A simple test is a dice game. Assuming that you throw 1 dice 1 times to get the result 6 probability is 1/6, then if I also throw 3 dice 100 times, the results are roughly as follows:

    • 0 x 6 = 57.9 times

    • One 6 = 34.7 times

    • 2 x 6 = 6.9 times

    • 3 x 6 = 0.5 times

Here is the code that implements 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 the PHP7 Random_int and the simple Rand function, you may get the following results

Sixes    expected    random_int0        579000      5794301        347000      3469272        69000 689853 5000        4658

If we see a better comparison of Rand and Random_int first, we can apply a formula to draw the result on the graph. The formula is: (PHP results-expected results)/expected results of 0.5 times.

The result diagram is as follows:

                  (values closer to 0 are better)

Although the results of 3 6 were not good and the test was too simple for practical use we can still see that random_int performance is better than Rand.

Further, the security level of our application is improved by the unpredictability and repeatable behavior of the random number generator.

Where's PHP5?

By default, PHP5 does not provide a strong random number generator. In fact, there are options such as openssl_random_pseudo_bytes (), Mcrypt_create_iv () or directly using the Fread () function to use/dev/random or/dev/urandom devices. There are also some 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 P Aragon Initiative Enterprises Random_compat Library. Random_compat Library allows you to project in PHP 5.x. Using Random_bytes () and Random_int ()

This library can be installed via composer:

Composer require paragonie/random_compatrequire ' vendor/autoload.php '; $string = random_bytes (+); Var_dump (Bin2Hex ($ string);//String ("8757a27ce421b3b9363b7825104f8bc8cf27c4c3036573e5f0d4a91ad2aaec6f" $int = Random_int (0,255); Var_dump ($int);//INT (81)

Random_compat libraries and PHP7 are used in different order:

    • Fread ()/dev/urandom if available

    • Mcrypt_create_iv ($bytes, Mcrypt_create_iv)

    • COM (' CAPICOM. Utilities.1 ')->getrandom ()

    • Openssl_random_pseudo_bytes ()

    • Want to know why this sequence is recommended for reading documentation.

A simple application of this library is used 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

Summarize

You should always use a cryptography-safe pseudo-random number generator, and the Random_compat library provides a good implementation.

If you want to use reliable random data sources, as you can see in this article, it is recommended to use Random_int and random_bytes as soon as possible.

  • Contact Us

    The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

    If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.