A detailed explanation of pseudo-random number and true random number of PHP

Source: Internet
Author: User
Tags generator hash md5 md5 hash rand

This article mainly introduces the pseudo random number and the true random number of PHP, this paper first explained the concept of true random number and pseudo random number, and gave a better pseudo-random number than using Mt_rand () function to produce a sample code, need friends can refer to the following

The first thing to declare is that the computer does not produce an absolutely random random number, and the computer can only produce "pseudorandom numbers". In fact, the absolute random random number is only an ideal random number, even if the computer development, it will not produce a series of absolute random random number. A computer can only generate a relative random number, or pseudo random number.

Pseudo-random number is not a false random number, here the "pseudo" is a regular meaning, is the computer generated pseudo-random number is both random and regular. How do you understand it? The pseudo-random numbers produced sometimes obey certain laws and sometimes do not obey any laws; some of the pseudorandom numbers obey certain rules; the other part does not follow any laws. For example, "There are no two leaves in the same shape," which is the characteristics of things, that is, randomness, but the leaves of each tree have an approximate shape, which is the commonness of things, that is, regularity. From this point of view, you will probably accept the fact that computers can only produce pseudo random numbers and cannot produce random numbers that are absolutely random.

First, let's take a look at the concept of true random numbers and pseudorandom numbers.

True random number generator: English is: true random number generators, referred to as: Trngs, is the use of unpredictable physical way to produce random numbers.

Pseudo-random number generator: English is: pseudo-random numbers generators, referred to as: PRNGs, is the computer using a certain algorithm to generate.

Compare the pictures of the random numbers produced by the two methods.

random.org (using atmospheric noise to generate random numbers, while atmospheric noise is produced by thunderstorms in the air) generates random bitmaps:

Random pictures generated by the rand () function of PHP under Windows:

It is obvious that the latter generation of pseudo random number generator images have this obvious stripe.

The code to produce this image using the rand random function of PHP is:

The code is as follows:

Need to open GD library

Header ("Content-type:image/png");

$im = Imagecreatetruecolor (512, 512)

Or Die ("Cannot Initialize new GD image Stream");

$white = Imagecolorallocate ($im, 255, 255, 255);

For ($y =0 $y <512; $y + +) {

For ($x =0 $x <512; $x + +) {

if (rand (0,1) = = 1) {

Imagesetpixel ($im, $x, $y, $white);

}

}

}

Imagepng ($im);

Imagedestroy ($im);

In fact, not all pseudo-random number generators (prngs) are so bad, just the same as the rand () function of PHP, which happens to be in Windows. If you test the same code under Linux, the resulting picture does not show any obvious stripes. It would be much better if you replaced the rand () function with the Mt_rand () function under Windows. This is due to the Mt_rand () using the Mersenne twister (horse plug rotation) algorithm to generate random numbers. PHP's documentation also says: Mt_rand () can produce random numbers at an average speed of four times times faster than the rand () provided by LIBC.

In addition, the Linux kernel (1.3.30) includes a random number generator/dev/random, which is sufficient for many security purposes.

The following is a description of the Linux random number generator principle:

The Linux operating system provides library data that is inherently random (or at least strongly random parts). This data usually comes from the device driver. For example, the keyboard driver collects information about the time between two keys and then fills the ambient noise into a random number generator library.

Random data is stored in the entropy pool (the Linux kernel maintains a entropy pool for collecting ambient noise from device drivers and other sources.) Theoretically, the data in the entropy pool is completely random and can produce the true random number sequence. To track the randomness of the data in the entropy pool, the kernel estimates the randomness of the data when it joins the data into the pool, a process called entropy estimation. The entropy estimate value describes the number of random digits contained in the pool, and the greater the value, the better the randomness of the data in the pool. ), it "stirs" each time new data is entered. This mixing is actually a mathematical transformation that helps to improve randomness. When the data is added to the entropy pool, the system estimates how many real random bits are obtained.

It is important to determine the total amount of randomness. The problem is that certain quantities tend to be less random than they seem at first. For example, adding that a 32-digit number of seconds since the last time you press the keyboard does not actually provide new 32-bit random information, because most keys are very close.

After the bytes are read from the/dev/random, the entropy pool uses the MD5 algorithm for the password hash, and the bytes in the hash are converted to numbers and then returned.

If there are no random bits available in the entropy pool, the/dev/random waits before there is enough randomness in the pool and does not return the result. This means that if you use/dev/random to produce a lot of random numbers, you'll find it too slow and not practical. We often see/dev/random generate dozens of bytes of data, and then do not produce results for many seconds.

Fortunately, another interface with the entropy pool can circumvent this limitation:/dev/urandom. Even if there is no randomness available in the entropy pool, the replacement device always returns random numbers. If you take out a lot of numbers without giving the entropy pool enough time to fill it again, you won't get the benefit of sharing entropy from various sources, but you can still get very good random numbers from the MD5 hash of the entropy pool! The problem with this approach is that if anyone cracked the MD5 algorithm, And by looking at the output to get information about the hash input, your number will immediately become completely predictable. Most experts agree that the analysis is not feasible in terms of calculation. However,/dev/urandom is still considered to be "unsafe" (and often questionable) than/dev/random.

There is no/dev/random available under Windows, but you can use the Capicom.utilities object provided by Microsoft's "CAPICOM.dll".

Here's a sample code that uses PHP to produce a better pseudo-random number than using the Mt_rand () function:

The code is as follows:

  

Get 128 pseudorandom bits in a string bytes

$PR _bits = ';

Unix/linux platform?

$fp = @fopen ('/dev/urandom ', ' RB ');

if ($fp!== FALSE) {

$PR _bits. = @fread ($fp, 16);

@fclose ($FP);

}

Ms-windows platform?

if (@class_exists (' COM ')) {

try {

$CAPI _util = new COM (' CAPICOM. Utilities.1 ');

$PR _bits. = $CAPI _util->getrandom (16,0);

If we are binary data PHP munges it, so we

Request Base64 return value. We Squeeze out the

Redundancy and useless ==crlf by hashing ...

if ($pr _bits) {$PR _bits = MD5 ($PR _bits,true);}

catch (Exception $ex) {

Echo ' Exception: '. $ex->getmessage ();

}

}

if (strlen ($PR _bits) < 16) {

Do something to warn system owner

pseudorandom generator is missing

}

?>

So PHP to generate a true random number or to call the external elements to support!

Note < > : More Wonderful tutorials please focus on Triple programming

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.