Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

generate a 16 character unique key in java

Tags:

java

hashcode

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?

like image 996
Swagatika Avatar asked Feb 18 '23 22:02

Swagatika


2 Answers

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(...);
like image 81
Ingo Kegel Avatar answered Feb 27 '23 10:02

Ingo Kegel


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

like image 20
korifey Avatar answered Feb 27 '23 11:02

korifey