Click to See Complete Forum and Search --> : Generate hash for session purposes


atad6
02-22-2005, 11:02 AM
Hi,
I'm new to php and I was wondering if someone could take a look at my code. It's a function that generates a random md5 hash to be used for session keys. I was wondering about whether I should use this method or not and how the code looks. Thanks!


function ghash($length = 8)
{
for ($x = 1; $x <= $length; $x++)
{
$n = rand(1,2);
switch($n)
{
case 1:
$an = rand(1,26);
$aa = range('a', 'z');
$h = $h . $aa[$an];
break;

case 2:
$an = rand(0,9);
$h = $h . $an;
break;
}
}
$hash = md5($h);

return $hash;
}

laserlight
02-22-2005, 12:03 PM
Here's a simplication of your function.
Basically, I have shifted the declaration of the ranges to outside the loop, which will save you much time.
Since there are only 2 possible values to be tested, a simple if conditional is better than a switch structure.

function ghash($length = 8)
{
$h = '';
$alpha = range('a', 'z');
$numeric = range(0, 9);
for ($x = 0; $x < $length; $x++)
{
if (mt_rand(0, 1))
{
$h .= $alpha[mt_rand(0, 25)];
}
else
{
$h .= $numeric[mt_rand(0, 9)];
}
}
return md5($h);
}

That said, since you are using ghash() to provide a session key, limiting the entropy so greatly is just asking for trouble.
With the default length there is only 36**8=2821109907456 possible combinations, smaller than even the cube root of the number of possible MD5 hashes!

Also, while SHA1 is theoretically broken collion-wise, MD5 is even more so, so I recommend that you use SHA1 instead.
A simple solution might then be:
function ghash($salt = '')
{
return sha1($salt.mt_rand().mt_rand().mt_rand().mt_rand());
}

atad6
02-22-2005, 09:41 PM
I understand that I should use a better method for generating a hash, I just have a question about the code that you edited for me. I want to get better at PHP and I had a question about the code I don't understand how this segment will work
if (mt_rand(0, 1))
I don't understand how the mt_rand function validates a conditional statement. I was just wondering how this works, thanks!

Weedpacket
02-23-2005, 05:36 AM
That mt_rand() function returns an integer between 0 and 1 inclusive. In other words, it returns either 0 or 1 (randomly).

In PHP's typing rules (http://nz2.php.net/manual/en/language.types.type-juggling.php), 0 is equivalent to false, and 1 is equivalent to true.

atad6
02-23-2005, 09:37 AM
Thanks!