How to generate cryptographically random numbers?

How do you generate cryptographically secure random numbers with PHP?

  • Possible Duplicate: http://stackoverflow.com/questions/1182584/secure-random-number-generation-in-php 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.

  • Answer:

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

Travis at Stack Overflow Visit the source

Was this solution helpful to you?

Other answers

Depending on your platform, you may use /dev/urandom or CAPICOM. This is nicely summarized in http://www.php.net/manual/en/function.mt-rand.php#83655.

codehead

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

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

Eimantas

Related Q & A:

Just Added Q & A:

Find solution

For every problem there is a solution! Proved by Solucija.

  • Got an issue and looking for advice?

  • Ask Solucija to search every corner of the Web for help.

  • Get workable solutions and helpful tips in a moment.

Just ask Solucija about an issue you face and immediately get a list of ready solutions, answers and tips from other Internet users. We always provide the most suitable and complete answer to your question at the top, along with a few good alternatives below.