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

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
User avatar
aditya2071990
Forum Contributor
Posts: 106
Joined: Thu May 22, 2008 11:30 am
Location: Hyderabad, India
Contact:

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

Post 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?
User avatar
onion2k
Jedi Mod
Posts: 5263
Joined: Tue Dec 21, 2004 5:03 pm
Location: usrlab.com

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

Post 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
User avatar
aditya2071990
Forum Contributor
Posts: 106
Joined: Thu May 22, 2008 11:30 am
Location: Hyderabad, India
Contact:

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

Post by aditya2071990 »

Thanks
Post Reply