Skip to content

Instantly share code, notes, and snippets.

@gautier-levert
Created October 21, 2014 20:06
Show Gist options
  • Save gautier-levert/a6881cff798e5f53b3fb to your computer and use it in GitHub Desktop.
Save gautier-levert/a6881cff798e5f53b3fb to your computer and use it in GitHub Desktop.
Java - random password generation
import java.security.SecureRandom;
import java.util.Random;
/**
* @author softdev7
*/
public class RandomPasswordGenerator {
private static final Random RANDOM = new SecureRandom();
private static final String ALPHA_CAPS = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
private static final String ALPHA = "abcdefghijklmnopqrstuvwxyz";
private static final String NUM = "0123456789";
private static final String SPL_CHARS = "!@#$%^&*_=+-/";
private static final String ALL_CHARS = ALPHA_CAPS + ALPHA + NUM + SPL_CHARS;
private static int[] randomIndexes(int len) {
int[] indexes = new int[len];
for (int i = 0; i < len; i++) {
indexes[i] = i;
}
for (int i = len - 1, j, t; i > 0; i--) {
j = RANDOM.nextInt(i);
t = indexes[j];
indexes[j] = indexes[i];
indexes[i] = t;
}
return indexes;
}
public static String generatePswd(int minLen, int maxLen, int noOfCAPSAlpha,
int noOfDigits, int noOfSplChars) {
if (minLen > maxLen) {
throw new IllegalArgumentException("Min. Length > Max. Length!");
}
if ((noOfCAPSAlpha + noOfDigits + noOfSplChars) > minLen) {
throw new IllegalArgumentException
("Min. Length should be atleast sum of (CAPS, DIGITS, SPL CHARS) Length!");
}
int len = RANDOM.nextInt(maxLen - minLen + 1) + minLen;
int[] indexes = randomIndexes(len);
char[] pswd = new char[len];
int j = 0;
for (; j < noOfCAPSAlpha; j++) {
pswd[indexes[j]] = ALPHA_CAPS.charAt(RANDOM.nextInt(ALPHA_CAPS.length()));
}
for (; j < (noOfCAPSAlpha + noOfDigits); j++) {
pswd[indexes[j]] = NUM.charAt(RANDOM.nextInt(NUM.length()));
}
for (; j < (noOfCAPSAlpha + noOfDigits + noOfSplChars); j++) {
pswd[indexes[j]] = SPL_CHARS.charAt(RANDOM.nextInt(SPL_CHARS.length()));
}
for (; j < len; j++) {
pswd[indexes[j]] = ALPHA.charAt(RANDOM.nextInt(ALPHA.length()));
}
return new String(pswd);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment