Created
April 9, 2009 18:33
-
-
Save raykrueger/92654 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
import org.apache.commons.codec.binary.Hex; | |
import java.security.MessageDigest; | |
import java.security.NoSuchAlgorithmException; | |
import java.security.SecureRandom; | |
/** | |
* @author Ray Krueger | |
*/ | |
public abstract class SimpleUID { | |
public static final int MAX_LEN = 40; | |
public static final int MIN_LEN = 16; | |
private static final String ALGORITHM = "SHA1"; | |
private static final SecureRandom RANDOM = new SecureRandom(); | |
public static String generate() { | |
byte[] bytes = new byte[64]; | |
RANDOM.nextBytes(bytes); | |
try { | |
bytes = MessageDigest.getInstance(ALGORITHM).digest(bytes); | |
} catch (NoSuchAlgorithmException e) { | |
throw new RuntimeException(e); | |
} | |
return new String(Hex.encodeHex(bytes)); | |
} | |
public static String generate(final int length) { | |
if (length < MIN_LEN) { | |
throw new IllegalArgumentException("length must be greater than " + MIN_LEN + " to be useful"); | |
} | |
if (length > MAX_LEN) { | |
throw new IllegalArgumentException("length must not be greater than " + MAX_LEN); | |
} | |
return generate().substring(0, length); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment