Secure random number generation in PHP

Viewed 39755

Use case: the "I forgot my password" button. We can't find the user's original password because it's stored in hashed form, so the only thing to do is generate a new random password and e-mail it to him. This requires cryptographically unpredictable random numbers, for which mt_rand is not good enough, and in general we can't assume a hosting service will provide access to the operating system to install a cryptographic random number module etc. so I'm looking for a way to generate secure random numbers in PHP itself.

The solution I've come up with so far involves storing an initial seed, then for each call,

result = seed
seed = sha512(seed . mt_rand())

This is based on the security of the sha512 hash function (the mt_rand call is just to make life a little more difficult for an adversary who obtains a copy of the database).

Am I missing something, or are there better known solutions?

4 Answers

How about something like

<?
$length = 100;
$random = substr(hash('sha512', openssl_random_pseudo_bytes(128)), 0, $length);

I just noticed its about numbers, so heres the solution for numbers:

<?
$max = 1000;
$random = (unpack('n', openssl_random_pseudo_bytes(2))[1] * time()) % $max;
Related