3 ms·
For example, here's one way to generate a random, fixed-length key in PHP: md5(uniqid(rand(), true)) Bad example. The obfuscation is weak and easy to gue
by huhtenberg 17y ago
For example, here's one way to generate a random,
fixed-length key in PHP:
md5(uniqid(rand(), true))
Bad example. The obfuscation is weak and easy to guess. Just remember to salt your hashes, gentlemen, and you'll be fine (some conditions apply).
(edit) erm .. sorry, had a brain spasm and didn't notice the rand() .. :)
- likpok 17y agoHow is it easy to guess? The number it generates does not at all appear to be a function of the number of keys already assigned.
- cstejerean 17y agoIf they're simply using the md5 of a random number as a unique identifier in order to hide the total number of records in the database I fail to see security implications of not using a salt.
- teej 17y agoI've gotten in the habit of using: SHA1(unix_timestamp + "misc salt phrase" + rand )[0, 8] It gives a nice, simple, 8 character id, pretty much not likely to create a collision in a space of 1M keys, and not guessable. Am i doing it wrong?
- jhancock 17y agothis is just fine. you are only at risk if your db libs/frameworks have no checks for if collision does some day occur. For example, as an id being a primary key in a db table, your db will cough up an error if you get collision, but will your ruby/python/blub libs/frameworks handle it gracefully?
- CalmQuiet 17y agoIs it not a simple thing to require "unique" of the table column? ...and then if the occasional "error" occurs in attempt to create a new row in table have your framework retry until your randomizing routine succeeds in generating an unused ID? Or am I missing something?
- edw519 17y ago"pretty much not likely to create a collision" Depends on your definition of "pretty much not likely". It may be far more likely than you suspect. Remember that in a group of 30 people, there's a 50% chance 2 of them have the same birthday. Not exactly intuitive. Also remember that as your data base grows, the probability of collisions grows geometrically. Here's hoping that your app does so well that you'll need millions of IDs.
- teej 17y ago> Remember that in a group of 30 people, there's a 50% chance 2 of them have the same birthday. Not exactly intuitive. It's closer to 70%. You're very much correct, with my example, the chance of a collision is very, very high. I recalculated the odds, and by increasing the ID length to 12 (still a manageable size from a human readable standpoint), the odds of hitting a collision from 1M ids drops down to 0.1%. You can also just use sequences like someone mentioned earlier or seed your hash with something checked for uniqueness in advance, like a username. There seem to be plenty of ways of doing this right, just not my way!
- eli 17y agowhy not just timestamp + rand? (And make rand as many digits as needed to make it as long as you want)