I've got this issue - my password needs to have a minimum of 8 chars and have at least:
- 1 capital letter
- 1 lowercase letter
- 1 special character
The function works almost as intended except sometimes it doesn't fulfill the requirements of the password listed above. How do I fix my code to ensure it meets the requirements every time it gets generated?
public class PasswordGenerator {
private static final String CAPITAL_LETTERS = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
private static final String LOWERCASE_LETTERS = "abcdefghijklmnopqrstuvwxyz";
private static final String NUMBERS = "0123456789";
private static final String SPECIAL_CHARACTERS = "!@#$%^&*_=+-/.?<>)";
private static final String PASSWORD_BASE = CAPITAL_LETTERS + LOWERCASE_LETTERS + NUMBERS + SPECIAL_CHARACTERS;
public static String generateRandomPassword() {
Random random = new Random();
int randomPasswordLength = 8 + random.nextInt(7);
System.out.println("random password length: " + randomPasswordLength);
char[] generatedPassword = new char[randomPasswordLength];
for(int i=0; i<randomPasswordLength; i++) {
generatedPassword[i] = PASSWORD_BASE.charAt(random.nextInt(PASSWORD_BASE.length()));
}
return new String(generatedPassword);
}