Implement PasswordBuilder

This commit is contained in:
Marcel Schwarz 2020-03-18 01:00:23 +01:00
parent ba29ab927d
commit ca1b4e3802

View File

@ -0,0 +1,88 @@
package de.icaotix.generator;
import java.util.LinkedList;
import java.util.Random;
public class PasswordBuilder {
private static final String UPPERCASE_LETTERS = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
private static final String LOWERCASE_LETTERS = UPPERCASE_LETTERS.toLowerCase();
private static final String NUMBERS = "1234567890";
private static final String SPECIAL_CHARACTERS = "~!@#()*^&%§?.,<>:/|[]{}=+_-";
private int length;
private int repeat;
private boolean appendUpper = true;
private boolean appendLower = true;
private boolean appendNumbers = true;
private boolean appendSpecial = false;
private String excludes;
public PasswordBuilder() {
this.length = 8;
this.repeat = 1;
}
public PasswordBuilder setLength(int length) {
this.length = length;
return this;
}
public PasswordBuilder setRepeat(int repeat) {
this.repeat = repeat;
return this;
}
public PasswordBuilder setExcludes(String excludes) {
this.excludes = excludes;
return this;
}
public PasswordBuilder useLowercase(boolean use) {
this.appendLower = use;
return this;
}
public PasswordBuilder useUppercase(boolean use) {
this.appendUpper = use;
return this;
}
public PasswordBuilder useNumbers(boolean use) {
this.appendNumbers = use;
return this;
}
public PasswordBuilder useSpecial(boolean use) {
this.appendSpecial = use;
return this;
}
public LinkedList<String> generate() {
final StringBuilder poolBuilder = new StringBuilder();
if (appendUpper) poolBuilder.append(UPPERCASE_LETTERS);
if (appendLower) poolBuilder.append(LOWERCASE_LETTERS);
if (appendNumbers) poolBuilder.append(NUMBERS);
if (appendSpecial) poolBuilder.append(SPECIAL_CHARACTERS);
String finalPool = poolBuilder.toString().replaceAll(excludes, "");
LinkedList<String> passwords = new LinkedList<>();
Random rand = new Random();
if (finalPool.length() < 1) return passwords;
for (int i = 0; i < repeat; i++) {
StringBuilder currPassword = new StringBuilder();
for (int j = 0; j < length; j++) {
currPassword.append(
finalPool.charAt(
rand.nextInt(finalPool.length())
)
);
}
passwords.add(currPassword.toString());
}
return passwords;
}
}