Page 1 of 1

Will this code ever fail to make a unique random string?

Posted: Thu Oct 09, 2008 3:18 am
by aditya2071990
Take a look at this code:

Code: Select all

function generateRandom($input){
    
    $random_number = intval( "0" . rand(1,9) . rand(0,9) . rand(0,9) . rand(0,9) . rand(0,9) ); // random(ish) 5 digit int
 
    $random_string = chr(rand(65,90)) . chr(rand(65,90)) . chr(rand(65,90)) . chr(rand(65,90)) . chr(rand(65,90)); // random(ish) 5 character string
    
    $randomSum = $random_number.$random_string.'adjafhdklf';
    
    $mostRandom = md5($randomSum.$input);
    
    return $mostRandom;
 
};
 
$one = generateRandom(generateRandom(generateRandom(generateRandom(456))));
 
$two = generateRandom(generateRandom(generateRandom(generateRandom(56456465465))));
 
echo $one;
 
echo '<br />';
echo '<br />';
 
echo 'Number of Characters = ';
 
echo strlen($one);
 
echo '<br />';
echo '<br />';
 
echo $two;
 
echo '<br />';
echo '<br />';
 
echo 'Number of Characters = ';
 
echo strlen($two);
Some of it, I got from php.net, but the rest, I wrote in a desperate attempt to make sure of uniqueness.

Still, I will always check for identical strings in the DB and re-execute the function in case there is a twin, but still, I was just curious to know if this code is vulnerable to generating identical strings...

I once heard from someone the md5(md5('something')) is actually weaker than md5('something'); does rand() have the same weakness? Is rand(rand()) less random, and produces more identical strings than rand() itself?

Re: Will this code ever fail to make a unique random string?

Posted: Thu Oct 09, 2008 4:09 am
by onion2k
Repeating a rand() makes it a lot weaker, so there's definitely a chance your code might fail.

Why aren't you using uniqid()? http://uk.php.net/uniqid

Re: Will this code ever fail to make a unique random string?

Posted: Thu Oct 09, 2008 8:22 am
by aditya2071990
Thanks