Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How is PHP's mt_rand seeded?

I know PHP's mt_rand() should not be used for security purposes as its results are not cryptographically strong. Yet a lot of PHP code does just that, or uses it as a fallback if better sources of randomness are not available.

So how bad is it? What sources of randomness does mt_rand use for seeding? And are there other security problems with mt_rand for cryptographic applications?

like image 997
JanKanis Avatar asked Jul 06 '12 08:07

JanKanis


People also ask

How does mt_ rand work?

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.

Is Mt_rand secure?

From http://php.net/manual/en/function.mt-rand.php: Caution This function does not generate cryptographically secure values, and should not be used for cryptographic purposes.

How do I generate a random number in PHP?

The rand() function generates a random integer. Example tip: If you want a random integer between 10 and 100 (inclusive), use rand (10,100). Tip: As of PHP 7.1, the rand() function has been an alias of the mt_rand() function.

What is Srand PHP?

Definition and Usage The srand() function seeds the random number generator (rand()). Tip: From PHP 4.2. 0, the random number generator is seeded automatically and there is no need to use this function.


1 Answers

In PHP 5.4, if mt_rand is automatically seeded the first time it's used (PHP source). The seed value is a function of the current timestamp, the PHP process PID and a value produced by PHP's internal LCG. I didn't check the source for previous versions of PHP, but the documentation implies that this seeding algorithm has been in use starting from PHP 5.2.1.

The RNG algorithm behind mt_rand is the Mersenne Twister. It doesn't really make sense to talk about "how bad" it is, because it's clearly documented (not on the PHP docs page, unfortunately) that it is entirely unsuitable for cryptographic applications. If you want crypto-strength randomness, use a documented crypto-strength generator.

Update: You might also want to look at this question from crypto.SE.

like image 198
Jon Avatar answered Oct 01 '22 13:10

Jon