-
Notifications
You must be signed in to change notification settings - Fork 71
/
Copy pathpasscode_generator.java
95 lines (79 loc) · 2.86 KB
/
passcode_generator.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
public final class PasswordGenerator {
private static final String LOWER = "abcdefghijklmnopqrstuvwxyz";
private static final String UPPER = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
private static final String DIGITS = "0123456789";
private static final String PUNCTUATION = "!@#$%&*()_+-=[]|,./?><";
private boolean useLower;
private boolean useUpper;
private boolean useDigits;
private boolean usePunctuation;
private PasswordGenerator() {
throw new UnsupportedOperationException("Empty constructor is not supported.");
}
private PasswordGenerator(PasswordGeneratorBuilder builder) {
this.useLower = builder.useLower;
this.useUpper = builder.useUpper;
this.useDigits = builder.useDigits;
this.usePunctuation = builder.usePunctuation;
}
public static class PasswordGeneratorBuilder {
private boolean useLower;
private boolean useUpper;
private boolean useDigits;
private boolean usePunctuation;
public PasswordGeneratorBuilder() {
this.useLower = false;
this.useUpper = false;
this.useDigits = false;
this.usePunctuation = false;
}
public PasswordGeneratorBuilder useLower(boolean useLower) {
this.useLower = useLower;
return this;
}
public PasswordGeneratorBuilder useUpper(boolean useUpper) {
this.useUpper = useUpper;
return this;
}
public PasswordGeneratorBuilder useDigits(boolean useDigits) {
this.useDigits = useDigits;
return this;
}
public PasswordGeneratorBuilder usePunctuation(boolean usePunctuation) {
this.usePunctuation = usePunctuation;
return this;
}
public PasswordGenerator build() {
return new PasswordGenerator(this);
}
}
public String generate(int length) {
// Argument Validation.
if (length <= 0) {
return "";
}
StringBuilder password = new StringBuilder(length);
Random random = new Random(System.nanoTime());
// Collect the categories to use.
List<String> charCategories = new ArrayList<>(4);
if (useLower) {
charCategories.add(LOWER);
}
if (useUpper) {
charCategories.add(UPPER);
}
if (useDigits) {
charCategories.add(DIGITS);
}
if (usePunctuation) {
charCategories.add(PUNCTUATION);
}
// Build the password.
for (int i = 0; i < length; i++) {
String charCategory = charCategories.get(random.nextInt(charCategories.size()));
int position = random.nextInt(charCategory.length());
password.append(charCategory.charAt(position));
}
return new String(password);
}
}