-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPasswordGenerator.java
More file actions
executable file
·62 lines (43 loc) · 1.98 KB
/
Copy pathPasswordGenerator.java
File metadata and controls
executable file
·62 lines (43 loc) · 1.98 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
59
60
61
62
import java.security.SecureRandom;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;
public class PasswordGenerator {
private static final String CHAR_LOWER = "abcdefghijklmnopqrstuvwxyz";
private static final String CHAR_UPPER = CHAR_LOWER.toUpperCase();
private static final String NUMBER = "0123456789";
private static final String OTHER_CHAR = "!@#$%&*()_+-=[]?";
private static final String PASSWORD_ALLOW_BASE = CHAR_LOWER + CHAR_UPPER + NUMBER + OTHER_CHAR;
// optional, make it more random
private static final String PASSWORD_ALLOW_BASE_SHUFFLE = shuffleString(PASSWORD_ALLOW_BASE);
private static final String PASSWORD_ALLOW = PASSWORD_ALLOW_BASE_SHUFFLE;
private static SecureRandom random = new SecureRandom();
public static void main(String[] args) {
System.out.format("String for password \t\t\t: %s%n", PASSWORD_ALLOW_BASE);
System.out.format("String for password (shuffle) \t: %s%n%n", PASSWORD_ALLOW);
// generate 5 random password
for (int i = 0; i < 5; i++) {
System.out.println("password : " + generateRandomPassword(15));
System.out.println("\n");
}
}
public static String generateRandomPassword(int length) {
if (length < 1) throw new IllegalArgumentException();
StringBuilder sb = new StringBuilder(length);
for (int i = 0; i < length; i++) {
int rndCharAt = random.nextInt(PASSWORD_ALLOW.length());
char rndChar = PASSWORD_ALLOW.charAt(rndCharAt);
// debug
System.out.format("%d\t:\t%c%n", rndCharAt, rndChar);
sb.append(rndChar);
}
return sb.toString();
}
// shuffle
public static String shuffleString(String string) {
List<String> letters = Arrays.asList(string.split(""));
Collections.shuffle(letters);
return letters.stream().collect(Collectors.joining());
}
}