


Detailed explanation of pseudo-random numbers and true random numbers in PHP_PHP Tutorial
Detailed explanation of pseudo-random numbers and true random numbers in PHP
This article mainly introduces the detailed explanation of pseudo-random numbers and true random numbers in PHP. This article first explains the true random numbers and Related concepts of pseudo-random numbers, and an example code that generates better pseudo-random numbers than using the mt_rand() function is given. Friends in need can refer to it
The first thing that needs to be stated is that computers do not generate absolutely random numbers. Computers can only generate "pseudo-random numbers". In fact, absolutely random numbers are just ideal random numbers. No matter how the computer develops, it will not generate a string of absolutely random numbers. Computers can only generate relatively random numbers, that is, pseudo-random numbers.
Pseudo-random numbers are not pseudo-random numbers. The "pseudo" here means regular, which means that the pseudo-random numbers generated by computers are both random and regular. How to understand it? The generated pseudo-random numbers sometimes follow certain rules and sometimes do not follow any rules; some of the pseudo-random numbers follow certain rules; the other part does not follow any rules. For example, "There are no two leaves with the same shape in the world." This points to the characteristics of things, that is, randomness, but the leaves of every tree have similar shapes, which is the commonality of things, that is, regularity. From this perspective, you will probably accept the fact that computers can only generate pseudo-random numbers but cannot generate absolutely random numbers.
First, let’s understand the concepts of true random numbers and pseudo-random numbers.
True random number generators: English: true random number generators, abbreviated as: TRNGs, are random numbers generated by unpredictable physical methods.
Pseudo-random number generators: English: pseudo-random number generators, abbreviated as: PRNGs, are generated by computers using certain algorithms.
Compare the pictures of random numbers generated by the two methods.
Random bitmap generated by Random.org (which uses atmospheric noise to generate random numbers, which is generated by thunderstorms in the air):

Random pictures generated by PHP’s rand() function under Windows:

Obviously, the pictures generated by the latter pseudo-random number generator have these obvious stripes.
The code to use PHP’s rand random function to generate this picture is:
The code is as follows:
//Need to open the 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, it just happens that the rand() function of PHP under Windows is like this. If the same code is tested under Linux, the resulting picture will not show obvious stripes. Under Windows, if the mt_rand() function is used instead of the rand() function, the effect will be much better. This is because mt_rand() uses the Mersenne Twister algorithm to generate random numbers. The PHP documentation also says: mt_rand() can generate random values on average four times faster than the rand() provided by libc.
In addition, the Linux kernel (1.3.30 and above) includes a random number generator /dev/random, which is sufficient for many security purposes.
The following is an introduction to the principle of Linux random number generator:
The Linux operating system provides library data that is inherently random (or at least has components with strong randomness). This data usually comes from the device driver. For example, a keyboard driver collects information about the time between two key presses and then fills this ambient noise into a random number generator library.
Random data is stored in an entropy pool (the Linux kernel maintains an entropy pool to collect environmental noise from device drivers and other sources. In theory, the data in the entropy pool is completely random and can generate true random numbers Sequence. To track the randomness of the data in the entropy pool, the kernel estimates the randomness of the data when adding it to the pool. This process is called entropy estimation. The entropy estimate describes the number of random digits contained in the pool, and the larger the value. Indicates the more random the data in the pool is. ), it is "stirred" every time new data comes in. This stirring is actually a mathematical transformation that helps improve randomness. As data is added to the entropy pool, the system estimates how many truly random bits it has obtained.
It is important to measure the total amount of randomness. The problem is that some quantities are often less random than they appear when first considered. For example, adding a 32-bit number representing the number of seconds since the last keystroke was not actually providing a new 32-bit random information, since most keystrokes are close together.
After reading the bytes from /dev/random, the entropy pool uses the MD5 algorithm to hash the password. The individual bytes in the hash are converted into numbers and then returned.
If there are no randomness bits available in the entropy pool, /dev/random waits until there is enough randomness in the pool, without returning a result. This means that if you use /dev/random to generate many random numbers, you will find that it is too slow to be practical. We often see /dev/random generate dozens of bytes of data and then produce no results for many seconds.
Fortunately there is another interface to the entropy pool that can circumvent this limitation: /dev/urandom. This alternative device always returns random numbers even if no randomness is available in the entropy pool. If you take out many numbers without giving the entropy pool enough time to refill, you no longer get the benefit of pooled 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 cracks the MD5 algorithm and learns something about the hash input by looking at the output, your numbers immediately become completely predictable. Most experts agree that such an analysis is computationally unfeasible. However, /dev/urandom is still considered "less secure" (and generally 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".
The following is an example code that uses PHP to generate better pseudo-random numbers than the mt_rand() function:
The code is as follows:
// get 128 pseudorandom 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 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 that
// pseudorandom generator is missing
}
?>
Therefore, if PHP wants to generate true random numbers, it still needs to call external elements to support it!
Note< >: For more exciting tutorials, please pay attention to Bangke Home Programming

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



PHP 8.4 brings several new features, security improvements, and performance improvements with healthy amounts of feature deprecations and removals. This guide explains how to install PHP 8.4 or upgrade to PHP 8.4 on Ubuntu, Debian, or their derivati

Visual Studio Code, also known as VS Code, is a free source code editor — or integrated development environment (IDE) — available for all major operating systems. With a large collection of extensions for many programming languages, VS Code can be c

If you are an experienced PHP developer, you might have the feeling that you’ve been there and done that already.You have developed a significant number of applications, debugged millions of lines of code, and tweaked a bunch of scripts to achieve op

This tutorial demonstrates how to efficiently process XML documents using PHP. XML (eXtensible Markup Language) is a versatile text-based markup language designed for both human readability and machine parsing. It's commonly used for data storage an

JWT is an open standard based on JSON, used to securely transmit information between parties, mainly for identity authentication and information exchange. 1. JWT consists of three parts: Header, Payload and Signature. 2. The working principle of JWT includes three steps: generating JWT, verifying JWT and parsing Payload. 3. When using JWT for authentication in PHP, JWT can be generated and verified, and user role and permission information can be included in advanced usage. 4. Common errors include signature verification failure, token expiration, and payload oversized. Debugging skills include using debugging tools and logging. 5. Performance optimization and best practices include using appropriate signature algorithms, setting validity periods reasonably,

A string is a sequence of characters, including letters, numbers, and symbols. This tutorial will learn how to calculate the number of vowels in a given string in PHP using different methods. The vowels in English are a, e, i, o, u, and they can be uppercase or lowercase. What is a vowel? Vowels are alphabetic characters that represent a specific pronunciation. There are five vowels in English, including uppercase and lowercase: a, e, i, o, u Example 1 Input: String = "Tutorialspoint" Output: 6 explain The vowels in the string "Tutorialspoint" are u, o, i, a, o, i. There are 6 yuan in total

Static binding (static::) implements late static binding (LSB) in PHP, allowing calling classes to be referenced in static contexts rather than defining classes. 1) The parsing process is performed at runtime, 2) Look up the call class in the inheritance relationship, 3) It may bring performance overhead.

What are the magic methods of PHP? PHP's magic methods include: 1.\_\_construct, used to initialize objects; 2.\_\_destruct, used to clean up resources; 3.\_\_call, handle non-existent method calls; 4.\_\_get, implement dynamic attribute access; 5.\_\_set, implement dynamic attribute settings. These methods are automatically called in certain situations, improving code flexibility and efficiency.
