-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPasswordGenerator.java
More file actions
37 lines (33 loc) · 1.36 KB
/
PasswordGenerator.java
File metadata and controls
37 lines (33 loc) · 1.36 KB
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
import java.util.Random;
public class PasswordGenerator {
public final String UPPER = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
public final String LOWER = "abcdefghijklmnopqrstuvwxyz";
public final String DIGIT = "0123456789";
public final String SYMBOL = "@#$%&*=";
public String generatePassword(int length, boolean useUpper, boolean useLower, boolean useDigits, boolean useSymbol) {
StringBuilder allowedChars = new StringBuilder();
if (useUpper) {
allowedChars.append(UPPER);
}
if (useLower) {
allowedChars.append(LOWER);
}
if (useDigits) {
allowedChars.append(DIGIT);
}
if (useSymbol) {
allowedChars.append(SYMBOL);
}
if(allowedChars.length() == 0) {
throw new IllegalArgumentException("Error: At least one character type must be selected");
}
Random random = new Random();
StringBuilder password = new StringBuilder();
String allowed = allowedChars.toString();
for (int i = 0; i < length; i++) {
int index = random.nextInt(allowed.length()); // Randomly choose an index and get the character at that index from allowed characters
password.append(allowed.charAt(index));
}
return password.toString(); // Change StringBuilder to String and return
}
}