Created
January 15, 2015 15:04
-
-
Save yyunikov/af9855408839d7a2b867 to your computer and use it in GitHub Desktop.
Example of generating unique id's using sha256
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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