JavaAlgorithms/Others/PasswordGen.java

45 lines
1.2 KiB
Java
Raw Normal View History

package Others;
2020-10-24 18:23:28 +08:00
import java.util.ArrayList;
2017-10-22 21:11:27 +08:00
import java.util.Collections;
import java.util.List;
2020-10-24 18:23:28 +08:00
import java.util.Random;
2017-10-22 21:11:27 +08:00
/**
2020-10-24 18:23:28 +08:00
* Creates a random password from ASCII letters Given password length bounds
*
* @author AKS1996
* @date 2017.10.25
*/
2017-10-22 21:11:27 +08:00
class PasswordGen {
2020-10-24 18:23:28 +08:00
public static void main(String args[]) {
String password = generatePassword(8, 16);
System.out.print("Password: " + password);
}
2020-10-24 18:23:28 +08:00
static String generatePassword(int min_length, int max_length) {
Random random = new Random();
2017-10-22 21:11:27 +08:00
2020-10-24 18:23:28 +08:00
String upper = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
String lower = "abcdefghijklmnopqrstuvwxyz";
String numbers = "0123456789";
String specialChars = "!@#$%^&*(){}?";
2017-10-22 21:11:27 +08:00
2020-10-24 18:23:28 +08:00
String allChars = upper + lower + numbers + specialChars;
2017-10-22 21:11:27 +08:00
2020-10-24 18:23:28 +08:00
List<Character> letters = new ArrayList<Character>();
for (char c : allChars.toCharArray()) letters.add(c);
2017-10-22 21:11:27 +08:00
2020-10-24 18:23:28 +08:00
// Inbuilt method to randomly shuffle a elements of a list
Collections.shuffle(letters);
StringBuilder password = new StringBuilder();
2017-10-22 21:11:27 +08:00
2020-10-24 18:23:28 +08:00
// Note that size of the password is also random
for (int i = random.nextInt(max_length - min_length) + min_length; i > 0; --i) {
password.append(letters.get(random.nextInt(letters.size())));
2017-10-22 21:11:27 +08:00
}
2020-10-24 18:23:28 +08:00
return password.toString();
}
2017-10-22 21:11:27 +08:00
}