views:

75

answers:

3

I need a big(like, say, 128-bit big) random number generator in PHP. I was thinking in storing this number in a string as hexadecimal.

Note that this is meant for a login system that mentioned the need for a "random" number, so I'm guessing I really need it to be "random-enough"(because I know pseudo-random is never truly random).

The algorithm I was thinking was generating the number one hex digit at a time, then concatenating it all. Like this:

$random = '';
for ($i = 0; $i < 32; ++$i) {
   $digit = rand(0, 15);
   $random .= ($digit < 10 ? $digit : ($digit - 10 + 'a'));
}
return $random;

Can I trust this function to return good pseudo-random numbers or am I messing with something I really shouldn't?

+1  A: 

Try:

for ($str = '', $i = 0; $i < $len; $i++) {
    $str .= dechex(mt_rand(0, 15));
}
GZipp
A: 

I've often seen this handled in login systems by just doing something like:

$salt  = "big string of random stuff"; // you can generate this once like above
$token = md5( $salt . time()); // this will be your "unique" number

MD5 hashes can have collisions, but this is pretty effective and very simple.

julio
Why not just replace $salt by rand()? Wouldn't it be equally random? Heck, probably even more random.
luiscubal
that's true, but using rand() will negate your ability to compare the expected hash, if you want to do that. EG. in password situations, you often will hash the users' password with a salt-- then since you presumably are the only one who knows the salt, you can then compare the hash you've recorded in the DB for that user with the "expected hash", and you can verify that it's correct.
julio