4

I want to know what is the best approach in java to generate a 16 char unique key ? Is there any open source library which already provides such functionality. Also I need the uniqueness to be mentained even after server restart.

Could you suggest the best approach for above requirement.

Also could someone point me to, where can i get reference for writing a robust hashcode method where the hashcode would be genarated out of many alphanumeric fields?

Swagatika
  • 3,376
  • 6
  • 30
  • 39
  • 2
    To how important is it that the keys are unique? i.e. how much effort are you willing to go to? How robust is robust? – Peter Lawrey Oct 08 '12 at 12:59
  • 2
    Since the hash code is not guaranteed to be unique, it seems that is an entirely separate question. – Andrew Thompson Oct 08 '12 at 12:59
  • Well for starters you should include some encoded timestamp... – dngfng Oct 08 '12 at 13:00
  • Key should be unique as it will be inserted into db as primary key eventually. I want with less effort if this problem is alredy solved one. – Swagatika Oct 08 '12 at 13:03
  • For the hashcode part of question : I basically want to generate one unique ID which is calculated from 3/4 different alphanumeric fields and key's length has to be 16. – Swagatika Oct 08 '12 at 13:05
  • 5
    If it goes in a DB anyways, I'd start a DB sequence at `0` and prefix with `0000000000000000` and take the last 16 chars... Voila, guaranteed uniqueness - for a while at least... – Anders R. Bystrup Oct 08 '12 at 13:05
  • If you have a database and a table the key needs to be unique in, I would use it to generate the unique keys. I would use key as your 16-char "hash" – Peter Lawrey Oct 08 '12 at 13:05
  • This is a very similar question to this one: http://stackoverflow.com/questions/41107/how-to-generate-a-random-alpha-numeric-string-in-java – user1581900 Oct 08 '12 at 13:06
  • @PeterLawrey, could you point me to some example how can it be done with Oracle, and how to make sure the length of the key ? – Swagatika Oct 08 '12 at 13:09
  • Oracle supports AUTO INCREMENT http://docs.oracle.com/cd/E17952_01/refman-5.1-en/example-auto-increment.html but you can also use a SEQUENCE https://forums.oracle.com/forums/thread.jspa?threadID=2155886 You had best ask an Oracle expert the best way to do this in oracle. ;) – Peter Lawrey Oct 08 '12 at 13:12

2 Answers2

7

You could use the UUID class in the JRE. It generates a 128-bit key.

As for hash codes, this is also available in the JRE:

MessageDigest md = MessageDigest.getInstance("MD5");
byte[] hashCode = md.digest(...);
Ingo Kegel
  • 46,523
  • 10
  • 71
  • 102
  • Thanks Ingo. If you could point me to some example to leverage use of these classes that will be a great help. I have never used these classes earlier. Can I use MessageDigest for generating a 16 char unique key out of few alphanumeric fields ? – Swagatika Oct 08 '12 at 13:16
  • No, you should use UUID.randomUUID() for that. – Ingo Kegel Oct 08 '12 at 13:24
  • @Swagatika No, hash algorithms such as MD5 are not useful for generating unique keys (see Andrew Thompson's comment to your question). – Jesper Oct 08 '12 at 13:24
  • @Jesper : Can I sove both the problems 1. Generate a 16 C Unique Key, 2. Generate a 16C Unique Key with from some field values(i:e execution id, oredr id, etc) - with UUID ? – Swagatika Oct 08 '12 at 13:50
  • @Swagatika A random UUID does not have anything to do with field values (question 2). UUID = Universally Unique IDentifier. The algorithm to generate random UUIDs is so that the chance that you'll ever get an UUID that has been used before is almost zero. – Jesper Oct 08 '12 at 13:52
  • Ok, so if i ask in a different way is there way that I can generate unique key from a input string which in most cases would may not be be unique. – Swagatika Oct 08 '12 at 14:03
  • @Swagatika That does not makes sense. If you have a function that gives you a unique key, why would you worry about non-unique input strings? – Ingo Kegel Oct 08 '12 at 14:36
  • Im a little confused here... doesn't uuid.randomUUID() return a string that is 36 characters long? Like Swagatika, I need a 16 character long string that is unique. What am I missing? – cosbor11 Sep 24 '15 at 00:07
1
Random r = new SecureRandom();
byte[] b = new byte[16];
r.nextBytes(b);
String s = org.apache.commons.codec.binary.Base64.encodeBase64String(b);
return s.substring(0, 16); 

Good and robust way

korifey
  • 3,379
  • 17
  • 17
  • @David Hm, very funny. You can calculate the probability of collision in my way. It's 2^(-128), so can be neglected. How do you think GUID and UUID works? They use randomness inside and returns quazi-unique values (with small probability of collision). – korifey Oct 15 '12 at 16:28
  • But why distribute quasi-randomly at all - it isn't a requirement! If the question was random based, you answer would be hard to fault, but the risk of unnecessary collision is still a negative, however small. – David Grant Oct 16 '12 at 18:12
  • The answer is - for performance and simplicity reasons. E.g. you have a ditributed set of machines all over the world serving user's requests and want to generate unique id to each user request. Of course you can take one machine and call it "uniquity server" with database of all given request IDs. This is very hard (need to code much), low-performance, non-fault-tolearnt approach (if this server is down, nothing works). Or you can generate quazi-random IDs on each machine independenly with small probability of collision (in fact, almost all high-load internet services use this approach). – korifey Oct 29 '12 at 14:54