How is PHP's mt_rand seeded?
Asked
Viewed 8k times
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?
439k85 gold badges758 silver badges820 bronze badges
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.
7 Comments
You might find it interesting to know that /dev/random/ in FreeBSD, OpenBSD and OSX is filled by the Fortuna algorithm, which is cryptographically secure.
Following the PHP sources, it appears PHP's internal LCG is also seeded with the time and pid, so it doesn't add a lot of randomness. That link to crypto.stackexchange is also very revealing.
I'd like to add that for nearly all applications (including salt generation) you don't need crypto-safe random numbers.
@Somejan: I 'm not qualified to judge, but Wikipedia's "Disadvantages" section on MT says that it's a very good idea to seed MT with an LCG because it avoids the problematic case where MT is seeded with lots of zeroes and takes a lot of time to "break out" of that state.
Explore related questions
See similar questions with these tags.
