views:

448

answers:

4

We need to generate a cryptographically random string to use as an authentication token, which will be tied to session data in the database. We are using PHP, which doesn't appear to have a suitable random number generator built-in. How can we generate a cryptographically secure random string of N length using php?

Also note, due to the nature of our application, shell_exec is off the table.

+1  A: 

what about uniqid? docs have an example of how it can be used for cookies/sessions.

SilentGhost
This seems to be the best approach - when combined with mt_rand as described in the manual.
Travis
A: 

Off the top of my head: take micro time, multiply it by microtime % 100 and do few randoms on sha1 of received result.

Eimantas
That won't be very secure. Don't use the system clock unless you want the output to be predictable.
Dan Dyer
+2  A: 

Depending on your platform, you may use /dev/urandom or CAPICOM. This is nicely summarized in this comment from Mark Seecof.

codehead
Thanks - I do believe this is the best way, since /dev/urandom uses a variety of entropy sources, rather than just the system clock. In my case, however, we will not be able to use fopen in this manner because we're basically working in a sandboxed environment.
Travis
A: 

I think that you do not really need cryptographically secure random number for session handling. You can use built-in rand() function in for loop to get as much random symbols as you need. Or just stick to ol' trusty md5($salt.time().rand(10000).microtime())

n1313