Skip to content

Instantly share code, notes, and snippets.

@yyunikov
Created January 15, 2015 15:04
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save yyunikov/af9855408839d7a2b867 to your computer and use it in GitHub Desktop.
Save yyunikov/af9855408839d7a2b867 to your computer and use it in GitHub Desktop.
Example of generating unique id's using sha256
public final class ObjectIdUtils {
private static final Logger LOGGER = LoggerFactory.getLogger(ObjectIdUtils.class);
private static final char[] BASE36 = {
'0', '1', '2', '3', '4', '5',
'6', '7', '8', '9', 'A', 'B',
'C', 'D', 'E', 'F', 'G', 'H',
'I', 'J', 'K', 'L', 'M', 'N',
'O', 'P', 'Q', 'R', 'S', 'T',
'U', 'V', 'W', 'X', 'Y', 'Z'
};
private ObjectIdUtils() {
}
public static String getId(){
byte[] byteArray = ObjectId.get().toByteArray();
byte[] hash = sha256(byteArray);
return encodeAsBase36(Arrays.copyOf(hash, 7));
}
private static byte[] sha256(byte[] byteArray) {
try {
final Random rnd = new Random();
rnd.setSeed(System.currentTimeMillis());
MessageDigest digest = MessageDigest.getInstance("SHA-256");
byte[] salt = new byte[byteArray.length];
byte[] value = byteArray;
for(int i = 0; i < 1000; i++) {
rnd.nextBytes(salt);
digest.update(ObjectId.get().toByteArray());
value = digest.digest(value);
}
return value;
} catch (NoSuchAlgorithmException e) {
LOGGER.error("This should never happen because we using SHA-256 !!!", e);
return null;
}
}
private static String encodeAsBase36(byte[] input) {
char[] chars = new char[input.length];
for (int i = 0; i < input.length; i++) {
chars[i] = BASE36[(input[i] & 0xFF) % BASE36.length];
}
return new String(chars);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment