I had been working on generating the unique key for my progam. It’s not like generating the random password, it doesn’t need to be secure enough. It just need to be unpredictable.
There are lots of logic for hashing the key for many purpose. You can see detail list in wiki.
I also have some requirements for generating my unique key.
- can set the custom length. ( eg only 4 char: nG8c)
- should not have collision.
- fast enough to generate the million of key.
- i don’t want to check key if exist in DB.
Actually, it’s not possible to match with my requirement. Let’s say the character i used will be A-Z and 0-9. So the total character will be 36.
combination - 36^n
At least, it will have the collision if you are generating the million key with custom lenght 3.
36^3 = 46656
I’m still finding the better way to do that. Meanwhile, i found some interesting article and library.
article about how instagram generate their unique url.
nice library called http://hashids.org/. It’s a pretty good for generating the short unique ids from integer. The description from hashids about collisions
There is no collisions because the method is based off of integer to hex conversion. As long as you don’t change constructor arguments midway, the generated output will stay unique to your salt.
You can also test this by generating a billion ids and checking for collisions. Be sure to account for your alphabet, since default alphabet is case-sensitive (aaa is different than AAA).
I just thinking to reduce my requirment for my case after searching all this. If you have any suggestion, kindly mail to firstname.lastname@example.org