Uh oh!
There was an error while loading. Please reload this page.
- Notifications
You must be signed in to change notification settings - Fork 21.3k
Expand file tree
/
Copy pathPasswordGen.java
More file actions
Latest commit
55 lines (46 loc) · 2 KB
/
Copy pathPasswordGen.java
File metadata and controls
55 lines (46 loc) · 2 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
packagecom.thealgorithms.others;
importjava.util.ArrayList;
importjava.util.Collections;
importjava.util.List;
importjava.util.Random;
/**
* Creates a random password from ASCII letters Given password length bounds
*
* @author AKS1996
* @date 2017.10.25
*/
finalclassPasswordGen {
privatestaticfinalStringUPPERCASE_LETTERS = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
privatestaticfinalStringLOWERCASE_LETTERS = "abcdefghijklmnopqrstuvwxyz";
privatestaticfinalStringDIGITS = "0123456789";
privatestaticfinalStringSPECIAL_CHARACTERS = "!@#$%^&*(){}?";
privatestaticfinalStringALL_CHARACTERS = UPPERCASE_LETTERS + LOWERCASE_LETTERS + DIGITS + SPECIAL_CHARACTERS;
privatePasswordGen() {
}
/**
* Generates a random password with a length between minLength and maxLength.
*
* @param minLength The minimum length of the password.
* @param maxLength The maximum length of the password.
* @return A randomly generated password.
* @throws IllegalArgumentException if minLength is greater than maxLength or if either is non-positive.
*/
publicstaticStringgeneratePassword(intminLength, intmaxLength) {
if (minLength > maxLength || minLength <= 0 || maxLength <= 0) {
thrownewIllegalArgumentException("Incorrect length parameters: minLength must be <= maxLength and both must be > 0");
}
Randomrandom = newRandom();
List<Character> letters = newArrayList<>();
for (charc : ALL_CHARACTERS.toCharArray()) {
letters.add(c);
}
// Inbuilt method to randomly shuffle a elements of a list
Collections.shuffle(letters);
StringBuilderpassword = newStringBuilder();
// Note that size of the password is also random
for (inti = random.nextInt(maxLength - minLength) + minLength; i > 0; --i) {
password.append(ALL_CHARACTERS.charAt(random.nextInt(ALL_CHARACTERS.length())));
}
returnpassword.toString();
}
}