Thursday, March 31, 2011

mysql random generated value

I need to generate a random alpha/numeric to give to users that they come to the site to enter. I dont' know much about random numbers and such, I know there are seeding issues and such, but I'm not sure what they are.

So, I used this:

select substrING(md5(concat_ws('-',md5(username_usr), MD5(zip_usr), MD5(id_usr), MD5(created_usr))),-12) from users_usr

Is this safe? I used concat_ws because sometimes zip is null, but the others never are.

And yes, I know this is kinda short, but 1. They have to enter the last 4 of their social, 2. It's 1 time use, 3. There's no private data displayed back in the application and 4. I may use captcha, but since there's no private data, thats probably overkill.

THanks

From stackoverflow
  • Maybe using the Universal Unique Identifier would suffice? Just to keep it simple?

  • If you need a random alphanumeric value, why are you using so many variables? Something like the following should be perfectly enough:

    md5(rand())
    --Flavor: MySql
    
  • Someone in the deleted duplicate of this question suggested using UUID(), which I think is a good idea. I don't think there's anything greatly wrong with using MD5(RAND()) either.

    You'd have to store those, of course, which you don't have to do with your example.

    Anonymous : Changed my mind several times ;)
  • It'd help to know the purpose of the "random" string. This isn't random - it's repeatable - and fairly easily repeatable, at that. You're not exposing any sensitive information in a way that's easily reversible, but I'm guessing you're really looking for a way to generate a UUID (univeraslly unique ID). Not coincidentally, recent MySQL versions have a function called UUID.

    http://dev.mysql.com/doc/refman/5.0/en/miscellaneous-functions.html#function_uuid

    That might better solve the problem you're trying to address. If you really want a random number (which can definitely have collisions, by the way) for some reason, don't worry about seeding. If you don't specify a seed, it'll self-seed in a way that's probably better than a fixed seen anyway. You'd then map that random number (or a series of random numbers) to a character (possibly by casting the integer to a char), and repeat that until you have a string of chars long enough. But it bears repeating that a random number is not a guaranteed unique number...

0 comments:

Post a Comment