1

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

Leo
  • 1,508
  • 13
  • 27

1 Answers1

2

I prefer to generate a GUID. Here is some code that will do that for you.

 function getGUID(){
        if (function_exists('com_create_guid')){
            return com_create_guid();
        }else{
            mt_srand((double)microtime()*10000);//optional for php 4.2.0 and up.
            $charid = strtoupper(md5(uniqid(rand(), true)));
            $hyphen = chr(45);// "-"
            $uuid = chr(123)// "{"
                .substr($charid, 0, 8).$hyphen
                .substr($charid, 8, 4).$hyphen
                .substr($charid,12, 4).$hyphen
                .substr($charid,16, 4).$hyphen
                .substr($charid,20,12)
                .chr(125);// "}"
            return $uuid;
        }
    }

        $GUID = getGUID();
        echo $GUID;

Here is my source. http://guid.us/GUID/PHP

Rob S.
  • 1,044
  • 7
  • 25
  • +1 because I like GUID, but my question is more about if this is a good way to generate an unique and random key. Because it looks pritty simple but I'm wondering if there is a catch? – Leo Jun 01 '16 at 20:49
  • GUID is simple and extremely effective. If you need more convincing check out http://stackoverflow.com/questions/39771/is-a-guid-unique-100-of-the-time – Rob S. Jun 01 '16 at 21:04
  • Yes I know, but I wanna know if my idea would work or if there is something I forgot to think about? – Leo Jun 01 '16 at 21:06
  • 1
    as far as the method you are using looks fine to me, but my only question is why? when you create your own method, you actually add a systematic process to something that is "random". if you do that you become slightly less random. For that I would favor generating a guid over anything. – Rob S. Jun 01 '16 at 21:08