-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathpasswordgenerator
More file actions
58 lines (49 loc) · 2.64 KB
/
passwordgenerator
File metadata and controls
58 lines (49 loc) · 2.64 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
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
import java.security.SecureRandom;
public class PasswordGenerator {
private static final String LOWERCASE_LETTERS = "abcdefghijklmnopqrstuvwxyz";
private static final String UPPERCASE_LETTERS = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
private static final String NUMBERS = "0123456789";
private static final String SYMBOLS = "!@#$%^&*()_+-=[]{};':,.<>/?";
private static final String ALL_CHARACTERS = LOWERCASE_LETTERS + UPPERCASE_LETTERS + NUMBERS + SYMBOLS;
private static final SecureRandom SECURE_RANDOM = new SecureRandom();
public static String generatePassword(int length, boolean includeLowercaseLetters, boolean includeUppercaseLetters, boolean includeNumbers, boolean includeSymbols) {
if (length <= 0) {
throw new IllegalArgumentException("Length must be a positive integer");
}
StringBuilder characters = new StringBuilder();
if (includeLowercaseLetters) {
characters.append(LOWERCASE_LETTERS);
}
if (includeUppercaseLetters) {
characters.append(UPPERCASE_LETTERS);
}
if (includeNumbers) {
characters.append(NUMBERS);
}
if (includeSymbols) {
characters.append(SYMBOLS);
}
if (characters.length() == 0) {
throw new IllegalArgumentException("At least one character set must be included");
}
char[] password = new char[length];
password[0] = (includeLowercaseLetters || includeUppercaseLetters) ? (char)(SECURE_RANDOM.nextInt(26) + 'a') : NUMBERS.charAt(SECURE_RANDOM.nextInt(NUMBERS.length()));
for (int i = 1; i < length - 1; i++) {
password[i] = characters.charAt(SECURE_RANDOM.nextInt(characters.length()));
}
password[length - 1] = (includeLowercaseLetters || includeUppercaseLetters) ? (char)(SECURE_RANDOM.nextInt(26) + 'a') : NUMBERS.charAt(SECURE_RANDOM.nextInt(NUMBERS.length()));
return new String(password);
}
public static void main(String[] args) {
int length = 15;
boolean includeLowercaseLetters = true;
boolean includeUppercaseLetters = true;
boolean includeNumbers = true;
boolean includeSymbols = true;
String password = generatePassword(length, includeLowercaseLetters, includeUppercaseLetters, includeNumbers, includeSymbols);
while (!Character.isLetter(password.charAt(0)) || !Character.isLetter(password.charAt(password.length() - 1))) {
password = generatePassword(length, includeLowercaseLetters, includeUppercaseLetters, includeNumbers, includeSymbols);
}
System.out.println("Generated password: " + password);
}
}