PHP pseudo-random number and real random number details

Source: Internet
Author: User
Tags md5 hash
This article mainly introduces PHP's pseudo-random number and real random number details. This article first explains the concepts related to the real random number and pseudo-random number, and gives the comparison using mt_rand () an example code of a function to generate better pseudo-random numbers. if you need a friend, you can refer to the following first statement: The computer will not generate an absolute random number, and the computer can only generate a "pseudo-random number ". In fact, an absolute random number is just an ideal random number. even if the computer develops, it will not generate an absolute random number. A computer can only generate relative random numbers, that is, pseudo random numbers.

Pseudo-random numbers are not pseudo-random numbers. here, the "pseudo" is a regular meaning, that is, the pseudo-random numbers produced by computers are both random and regular. How can this problem be understood? The generated pseudo-random numbers sometimes follow certain rules, and sometimes do not follow any rules. some pseudo-random numbers follow certain rules, while others do not follow any rules. For example, "there are no two leaves in the same shape in the world." This is just the characteristic of things, that is, randomness. However, the leaves of every tree have an approximate shape. this is the commonality of things, regularity. From this perspective, you will probably accept the fact that a computer can only generate pseudo-random numbers instead of absolute random numbers.

First, let's take a look at the concepts of real and pseudo-random numbers.

True random number generator: true random number generators (TRNGs) is a random number generated by unpredictable physical means.

Pseudo-random number generator: pseudo-random number generators (PRNGs), which is produced by computers using certain algorithms.

Compare the random numbers produced by the two methods.

Random bitmap generated by Random.org (a random number is generated by atmospheric noise, which is produced by thunderstorms in the air:

The random image generated by the rand () function of PHP in Windows:

Obviously, the image produced by the latter pseudo-random number generator has this obvious stripe.

The code for generating this image using php's rand random function is:

The code is as follows:

// You need to enable the gd Library
\$ Im = imagecreatetruecolor (512,512)
Or die ("Cannot Initialize new GD image stream ");
\$ White = imagecolorallocate (\$ im, 255,255,255 );
For (\$ y = 0 ;y 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) have such bad results, but the rand () function of PHP in Windows is like this. If the same code is tested in Linux, the generated image will not see obvious stripes. In Windows, if you use the mt_rand () function to replace the rand () function, the effect will be much better. This is because mt_rand () uses the Mersenne Twister algorithm to generate random numbers. The document in PHP also says: mt_rand () can generate random values at an average speed four times faster than the rand () provided by libc.

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

The following describes the principles of the random number generator in Linux:

Linux provides database data that is essentially random (or at least random. The data usually comes from the device driver. For example, the keyboard driver collects time information between two buttons and then fills in the environmental noise in the random number generator Library.

Random data is stored in the entropy pool (the Linux kernel maintains an entropy pool to collect environmental noise from device drivers and other sources. Theoretically, the data in the entropy pool is completely random and can generate a sequence of real random numbers. To track the availability of data in the entropy pool, the kernel adds the data to the pool to estimate the randomness of the data. this process is called entropy estimation. The entropy estimation value describes the number of random numbers in the pool. a greater value indicates a better randomness of the data in the pool. ), It is "stirred" every time a new data enters ". This agitation is actually a mathematical conversion that helps increase 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 some numbers are often less random than what was initially considered. For example, adding a 32-digit number of seconds since the last press on the keyboard does not actually provide new 32-bit random information, because most keys are very close.

After reading a byte from/dev/random, the entropy pool uses the MD5 algorithm for password hashing. each byte in the hash is converted to a number and then returned.

If no random bit is available in the entropy pool,/dev/random waits before the pool has enough randomness and no results are returned. This means that if you use/dev/random to generate many random numbers, you will find that it is too slow and not practical enough. We often see that/dev/random generates dozens of bytes of data and does not produce results in many seconds.

Fortunately, another interface with an entropy pool can bypass this restriction:/dev/urandom. Even if the entropy pool is available without randomness, this replacement device always returns a random number. If you retrieve a majority without giving enough time to refill the entropy pool, you will no longer be able to reap the benefits of entropy sharing from various sources; however, you can still obtain a very good random number from the MD5 hash of the entropy pool! The problem with this method is that if anyone has cracked the MD5 algorithm and learned about hash input through viewing the output, your number will become completely predictable immediately. Most experts believe that this analysis is not feasible in terms of computing. However, it is still considered that/dev/urandom is "insecure" than/dev/random (and usually suspect ).

No/dev/random is available in Windows, but you can use the capicom. Utilities object provided by Microsoft "CAPICOM. dll.

The following is an example code of using PHP to generate a better pseudo-random number than using the mt_rand () function:

The code is as follows:

<? Php
// Get 128 bytes udorandom bits in a string of 16 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 ask for binary data PHP munges it, so we
// Request base64 return value. We squeeze out
// 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 that
// Initialize udorandom generator is missing
}
?>

Therefore, PHP still needs to call external elements to generate real random numbers!

Related Keywords:

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.