Yesterday I overheard a conversation about rand()
and mt_rand()
, a collegue said that both of these are predictable and you should use different functions? I was wondering, I know rand()
is predictable in some way, and after some googling. Even mt_rand()
seems to be predictable if I readed this correctly.
For this I wrote a small piece of code, which creates an image:
<?php
header("Content-type: image/png");
$im = imagecreatetruecolor(512, 512) or die("Cannot Initialize new GD image stream");
$white = imagecolorallocate($im, 255, 255, 255);
$black = imagecolorallocate($im, 0, 0, 0);
for ($y = 0; $y < 512; $y++) {
for ($x = 0; $x < 512; $x++) {
if (rand(0, 1)) {
imagesetpixel($im, $x, $y, $white);
}
else{
imagesetpixel($im, $x, $y, $black);
}
}
}
imagepng($im); imagedestroy($im);
?>
this code outputs this image, as you can see it has some kind of pattern:
while the mt_rand()
function gave me this output:
now my question is, is mt_rand()
really that predictable, it seems pretty random to me compared to the rand()
function.
At the time, many applications used either rand() or mt_rand() to generate secret tokens or passwords. These functions are labeled cryptographically insecure, and as such should not be used for cryptographic purposes.
The mt_rand() function is a drop-in replacement for the older rand(). It uses a random number generator with known characteristics using the » Mersenne Twister, which will produce random numbers four times faster than what the average libc rand() provides.
Definition and Usage. The mt_rand() function generates a random integer using the Mersenne Twister algorithm. Example tip: If you want a random integer between 10 and 100 (inclusive), use mt_rand (10,100).
The rand() is an inbuilt function in PHP used to generate a random number ie., it can generate a random integer value in the range [min, max]. Syntax: rand(); The rand() function is used to generate a random integer.
Directly from the docs:
This function does not generate cryptographically secure values, and should not be used for cryptographic purposes. If you need a cryptographically secure value, consider using openssl_random_pseudo_bytes() instead.
mt_rand
generates better random numbers than rand
, and much faster. But that doesn't make it "secure" in the sense that it should be used for cryptography. Whether it's secure enough for your application is pretty subjective.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With