refactor: PasswordGen (#5373)

This commit is contained in:
Alex Klymenko
2024-08-24 10:57:40 +02:00
committed by GitHub
parent 4e72056527
commit 75355e87b6
2 changed files with 43 additions and 13 deletions

View File

@ -12,21 +12,32 @@ import java.util.Random;
* @date 2017.10.25
*/
final class PasswordGen {
private static final String UPPERCASE_LETTERS = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
private static final String LOWERCASE_LETTERS = "abcdefghijklmnopqrstuvwxyz";
private static final String DIGITS = "0123456789";
private static final String SPECIAL_CHARACTERS = "!@#$%^&*(){}?";
private static final String ALL_CHARACTERS = UPPERCASE_LETTERS + LOWERCASE_LETTERS + DIGITS + SPECIAL_CHARACTERS;
private PasswordGen() {
}
static String generatePassword(int minLength, int maxLength) {
/**
* Generates a random password with a length between minLength and maxLength.
*
* @param minLength The minimum length of the password.
* @param maxLength The maximum length of the password.
* @return A randomly generated password.
* @throws IllegalArgumentException if minLength is greater than maxLength or if either is non-positive.
*/
public static String generatePassword(int minLength, int maxLength) {
if (minLength > maxLength || minLength <= 0 || maxLength <= 0) {
throw new IllegalArgumentException("Incorrect length parameters: minLength must be <= maxLength and both must be > 0");
}
Random random = new Random();
String upper = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
String lower = "abcdefghijklmnopqrstuvwxyz";
String numbers = "0123456789";
String specialChars = "!@#$%^&*(){}?";
String allChars = upper + lower + numbers + specialChars;
List<Character> letters = new ArrayList<Character>();
for (char c : allChars.toCharArray()) {
List<Character> letters = new ArrayList<>();
for (char c : ALL_CHARACTERS.toCharArray()) {
letters.add(c);
}
@ -36,7 +47,7 @@ final class PasswordGen {
// Note that size of the password is also random
for (int i = random.nextInt(maxLength - minLength) + minLength; i > 0; --i) {
password.append(letters.get(random.nextInt(letters.size())));
password.append(ALL_CHARACTERS.charAt(random.nextInt(ALL_CHARACTERS.length())));
}
return password.toString();