Thursday, May 28, 2009

Generate hex string unique random ID

The code below is used to generate unique random ID in varchar with 10 chars in length. Though checking whether the ID generated had been used before in the table before inserting is still required, the probability of colliding ID is very low.

public String generateId() throws NoSuchAlgorithmException {
SecureRandom random = SecureRandom.getInstance("SHA1PRNG");
byte [] bytes = new byte[5];
random.nextBytes(bytes);
return byteArrayToHex(bytes);
}

public String byteArrayToHex(byte[] bytes) {
StringBuffer sb = new StringBuffer();
for (int i = 0; i < bytes.length; i++) {
String theHex = Integer.toHexString(bytes[i] & 0xFF).toUpperCase();
sb.append(theHex.length() == 1 ? "0" + theHex : theHex);
}
return sb.toString();
}