8

I'm generating a verification code to be used for account activation. You've probably seen this sort of thing before.

My question: if I were to generate this code with a complex formula like this:

md5(md5(time().'helloguys'.rand(0,9999)));

Is it really any better than generating just a random string of 32 characters and numbers like gj3dI3OGwo5Enf...?

dave
  • 1,043
  • 1
  • 10
  • 18
  • You might want to consider base32 encoding your result so that it is easier for your users to distinguish between characters that look similar in some fonts. – Bernard Chen Sep 09 '10 at 03:45
  • Aside from generating random value (i.e. verification number), if 2 users register and generate the exactly same verification code by accident, you might want to handle such case. If uniqueness matters, I think even mt_rand() might not suffice. – Meow Sep 09 '10 at 04:29
  • I'd think the verification codes would be stored in a database - put a unique key on the column, and prior to inserting the verification code, check if it already exists in the database, and keep generating new keys until you find one that hasn't been used previously. – Jake Petroules Sep 10 '10 at 17:21

2 Answers2

6

No, using the hash is not better. It would be more secure (less predictable) to pick 32 random characters. (Digits are characters.) Use a good ("cryptographic") random number generator, with a good seed (some bytes from /dev/random). Don't use time as a seed.

erickson
  • 265,237
  • 58
  • 395
  • 493
  • 2
    I was planning to generate the 32 random characters with a for loop. What's wrong with this method? And wouldn't it be fine for a normal site for account verification purposes. (I mean even if I were twitter or something, wouldn't that still be fine for the purpose at hand) – dave Sep 09 '10 at 03:38
  • Yes, I think picking the letters one at a time in a `for` loop would be fine, as long as the RNG is good it won't matter. This would be good for any site (might want a few more characters). – erickson Sep 09 '10 at 04:23
  • 1
    Also, avoid the use of characters that look similar. Don't include 0, O, 1, l or I as people trying to type the code in will make mistakes. – Andrew Kennan Sep 09 '10 at 04:39
  • 5
    @Andrew: No one should be typing this code... they'll either click the link, or if they can't, they ought to be copying and pasting. If they can't figure that out.. I'm surprised they made it into their email account. – mpen Sep 09 '10 at 07:13
1

Agree with erickson, just may advise you to use

pwgen -1 -s

command on *nix which will the job muich better of any procedure you may invent.

If you want to generate some string programmatically you may take a look at

<?php    
$better_token = md5(uniqid(rand(),1));
?>

this gives very good level of randomness and prior to collisions.

If you need even higher level of security you may consider to generate random sequences on http://www.random.org/

Igor
  • 2,619
  • 6
  • 24
  • 36