Skip to content

Instantly share code, notes, and snippets.

@somoso
Created November 30, 2016 22:44
Show Gist options
  • Save somoso/22a0cf09b4275ed61bebf98ff6e935e4 to your computer and use it in GitHub Desktop.
Save somoso/22a0cf09b4275ed61bebf98ff6e935e4 to your computer and use it in GitHub Desktop.
//http://stackoverflow.com/a/19597101/617028
private static char[] VALID_CHARACTERS =
"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456879".toCharArray();
// cs = cryptographically secure
public static String csRandomAlphaNumericString(int numChars) {
SecureRandom srand = new SecureRandom();
Random rand = new Random();
char[] buff = new char[numChars];
for (int i = 0; i < numChars; ++i) {
// reseed rand once you've used up all available entropy bits
if ((i % 10) == 0) {
rand.setSeed(srand.nextLong()); // 64 bits of random!
}
buff[i] = VALID_CHARACTERS[rand.nextInt(VALID_CHARACTERS.length)];
}
return new String(buff);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment