I want to give maybe a million password to some users that should be like:
A bit late, but I usually use the following code:
private static final int PASSWORD_SIZE = 16;
private static final String VALID_SPECIAL_CHARACTERS = "!@#$%&*()_-+=[]{}\\|:/?.,><"; // Note the double \ as escape
private static String createPassword() {
SecureRandom random = new SecureRandom();
StringBuilder password = new StringBuilder();
while (password.length() < PASSWORD_SIZE) {
char character = (char) random.nextInt(Character.MAX_VALUE);
if ((character >= 'a' && character <= 'z') || (character >= 'A' && character <= 'Z') || (character >= '0' && character <= '9') || VALID_SPECIAL_CHARACTERS.contains(String.valueOf(character))) {
password.append(character);
}
}
return password.toString();
}
There is no guarantee that there will always be a number, special character, lower-case and upper-case character in the password. This could be enforced by first adding a character and a digit, however this would create passwords that are a bit more predictable.