Muhammad Umer
Muhammad Umer

Reputation: 513

Generate small UID with uniqueness

I need to generate the UID (alphanumeric) for my use case but that should be a maximum of 7 characters long as we want UID to be random but manageable, like a PNR (CYB6KL) for example. Now if I am not wrong, I can generate a random UID that is small, but uniqueness might be compromised because of collisions (birthday paradox), so for 32 bits, 50% collision probability would be around 77k UID generations.

So in essence, I need a way to generate UIDs that are:

  1. Small (max 7 character)
  2. Random
  3. Unique
  4. Don't require lookups for the previous existance.

I will be storing this UID in a database column and it's imperative that the UID is unique. It will NOT be the table's primary key which right now is an autogenerated ID.

I am thinking of something along the lines, but I am not sure about uniqueness.

BigInteger big = new BigInteger(32, new SecureRandom());
return big.toString(32).toUpperCase();

Really appreciate any thoughts that might help on this. Generation must be unique.

Thanks in advance.

Upvotes: 0

Views: 634

Answers (1)

Christian Beikov
Christian Beikov

Reputation: 16400

You can use a library like hashids for this purpose which implements a bimorphic translation that can encode a numeric value into a string code with a custom alphabet. This should do exactly what you want. If you need this to be traversal-secure, you should use some kind of SecureRandom as source for the underlying numeric value. If not, you could even base this on the auto increment value you already have. The benefit of reusing the primary key is that you can just translate the string code and do a lookup by primary key.

Upvotes: 0

Related Questions