Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

is mt_rand() more secure than rand() [duplicate]

Tags:

php

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: rand() image

while the mt_rand() function gave me this output: mt_rand() image

now my question is, is mt_rand() really that predictable, it seems pretty random to me compared to the rand() function.

like image 524
Azrael Avatar asked Oct 07 '14 06:10

Azrael


People also ask

Is Mt_rand secure?

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.

What is the difference between Rand and Mt_rand?

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.

What is Mt_rand function in PHP?

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).

How to get a random number in PHP?

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.


1 Answers

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.

like image 76
meagar Avatar answered Sep 18 '22 18:09

meagar