mercredi 1 juin 2016

easiest way to generate an unique and random key

the question is not 'how to' generate such a key. There are tons of answers. Some are too simple like a timestamp but others are not unique enough like some chars with rand().

What I thougth is, why not combine both? If I take the timestamp in seconds or milliseconds and add random chars (but no numbers) in between, wouldn't that result a random and unique string?

The question is not specific to one programming language but to give you some code I made it in php:

$token = (string) preg_replace('/(0)\.(\d+) (\d+)/', '$3$1$2', microtime());
$l = strlen($token);
$c = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
for($i = 0; $i < $l; $i++){
    $token = substr_replace($token, $c[rand(0, 51)], rand(0, $l+$i), 0);
}

echo $token;

I'm realy looking forward for some randomness-pro's answer!

Thanks ;) Lenny




Aucun commentaire:

Enregistrer un commentaire