Which one of these two choices provides better randomness?
- From: luigi.perroti@xxxxxxxxxxxxxx
- Date: Mon, 28 Jul 2008 05:26:25 -0700 (PDT)
Hi all,
I'm coding a simple PHP application that will store an user's session
id
as a cookie.
Since I would like to avoid dealing with the session id generation
features of PHP, I tried coming up with something quite simple.
At the beginning I thought about using a SHA-512 hash of a random
sequence of bytes.
This is the relevant code:
$randomSequence = mcrypt_create_iv(8, MCRYPT_DEV_URANDOM);
$id = hash('sha512', $randomSequence);
Now, I suppose that this is reasonably random.
At least for a site that doesn't store any financial or personal data
about its users.
In the hope of generating an even more random value, I came up with
this
code:
// Generate the random sequence
$randomSequence = mcrypt_create_iv(8,MCRYPT_DEV_URANDOM);
// Calculate the hash
$tmp = hash('sha512', $randomSequence);
// Append to the hash a timestamp and then calculate another hash
$tmp2 = hash('sha512', $tmp . microtime());
// Concatenate the two hashes
$tmp = $tmp . $tmp2;
// Get a random number between 0 and 72
$randomStart = mt_rand(0,72);
// The session id is a substring of $tmp.
// 200 characters long and starting from $randomStart
$id = substr($tmp, $randomStart, 200);
In the eyes of a person without the necessary knowledge on these
matters, just like me, the second method could be easily regarded
as "more random" than the first one.
But then again it might as well be very possible that I'm "removing
entropy" or something along these lines.
To avoid shooting myself in the feet I'd really like to hear your
opinion on which method I should follow.
Thanks for reading,
Luigi
.
- Follow-Ups:
- Re: Which one of these two choices provides better randomness?
- From: Kristian Gjøsteen
- Re: Which one of these two choices provides better randomness?
- Prev by Date: Re: A question about current safe hash algorithm(Is SHA256 safe enough?)
- Next by Date: Re: Which one of these two choices provides better randomness?
- Previous by thread: A question about current safe hash algorithm(Is SHA256 safe enough?)
- Next by thread: Re: Which one of these two choices provides better randomness?
- Index(es):
Relevant Pages
|