Swagatika
Swagatika

Reputation: 3436

generate a 16 character unique key in java

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?

Upvotes: 4

Views: 9576

Answers (2)

Ingo Kegel
Ingo Kegel

Reputation: 47995

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(...);

Upvotes: 7

korifey
korifey

Reputation: 3509

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

Upvotes: 1

Related Questions