Random Number of PHP authenticity

Source: Internet
Author: User
Tags md5 hash
This paper mainly introduces the pseudo-random number and the real random number of PHP, this paper first explains the relevant concepts of true random number and pseudo-random number, and gives a example code that produces better pseudo-random numbers than the Mt_rand () function. We hope to help you.

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

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

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

True random number generator: in English: True random number generators, referred to as: Trngs, is the use of unpredictable physical means to generate random numbers.

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

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

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

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

Obviously, the latter pseudo-random number generator produces pictures that have this obvious stripe.

The code that uses the rand random function of PHP to generate this image is:

You need to open the GD Library header ("Content-type:image/png"); $im = Imagecreatetruecolor (up to,) 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 (ran D (0,1) = = 1) {Imagesetpixel ($im, $x, $y, $white);}} Imagepng ($im); Imagedestroy ($im);


In fact, not all pseudo-random number generators (prngs) effects are so bad, just the rand () function of PHP that happens to be in Windows. If you test the same code under Linux, the resulting image will not show any noticeable stripes. It would be much better to replace the rand () function with the Mt_rand () function under Windows. This is because Mt_rand () uses the Mersenne Twister (horse's plug rotation) algorithm to generate random numbers. The PHP document also says that the average speed of mt_rand () can produce random values four times times faster than the rand () provided by LIBC.

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

Here is an introduction to the principle of random number generators for Linux:

The Linux operating system provides library data that is inherently random (or at least has a strongly random part). 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 the random number generator library.

Random data is stored in the entropy pool (the Linux kernel maintains an entropy pool used to collect ambient noise from device drivers and other sources.) In theory, the data in the entropy pool is completely random and can be realized by generating a sequence of true random numbers. To track the randomness of the data in the entropy pool, the kernel estimates the randomness of the data when it joins the data to the pool, a process called entropy estimation. The entropy estimate describes the number of random digits contained in the pool, and the larger the value, the better the randomness of the data in the pool. ), it "stirs" each time a new data entry is entered. This agitation is actually a mathematical conversion 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 thought. For example, adding a 32-digit number that represents the number of seconds since the last press of the keyboard actually does not 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 password hashing, and the individual bytes in the hash are converted to numbers and returned.

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

Fortunately, there is another interface to the entropy pool that bypasses this limitation:/dev/urandom. Even if no randomness is available in the entropy pool, the replacement device always returns a random number. If you take out many numbers without giving the entropy pool enough time to re-fill, you can no longer get the benefit of the entropy of the various sources, but you still get very good random numbers from the MD5 hash of the entropy pool! The problem with this approach is that if anyone has cracked the MD5 algorithm and learned the information about the hash input by looking at the output, then your number will immediately become fully predictable. Most experts agree that this analysis is not feasible from a computational standpoint. 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 objects provided by Microsoft's "CAPICOM.dll".

Here is an example code that uses PHP to produce a better pseudo-random number than the Mt_rand () function:

<?php//get pseudorandom bits in a string of bytes$pr_bits = ";//Unix/linux platform? $fp = @fopen ('/dev/urando M ', ' RB '), if ($fp!== FALSE) {$pr _bits. = @fread ($fp, +); @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 Base6 4 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) <) {//do something to warn system owner that//pseudorandom Generator is missing}?>

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

Related recommendations:

PHP random number C Extended random number

In-depth comprehension based on PHP random numbers

PHP function: Generate n non-repeating random number, PHP random number _php Tutorial

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.