|
| 1 | +import java.security.NoSuchAlgorithmException; |
| 2 | +import java.security.SecureRandom; |
| 3 | +import java.util.Random; |
| 4 | + |
| 5 | +public class PasswordGenerator { |
| 6 | + private static final String UPPER = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"; |
| 7 | + private static final String LOWER = "abcdefghijklmnopqrstuvwxyz"; |
| 8 | + private static final String DIGITS = "0123456789"; |
| 9 | + private static final String SPECIAL = "!@#$%^&*()-_=+[]{}|;:'\",.<>?"; |
| 10 | + |
| 11 | + public static String generatePassword(int length, boolean useUpper, boolean useLower, boolean useDigits, boolean useSpecial) { |
| 12 | + if (length <= 0) { |
| 13 | + throw new IllegalArgumentException("Password length must be greater than 0"); |
| 14 | + } |
| 15 | + |
| 16 | + StringBuilder characters = new StringBuilder(); |
| 17 | + if (useUpper) characters.append(UPPER); |
| 18 | + if (useLower) characters.append(LOWER); |
| 19 | + if (useDigits) characters.append(DIGITS); |
| 20 | + if (useSpecial) characters.append(SPECIAL); |
| 21 | + |
| 22 | + if (characters.length() == 0) { |
| 23 | + throw new IllegalArgumentException("At least one character type (upper, lower, digits, special) must be selected"); |
| 24 | + } |
| 25 | + |
| 26 | + Random random; |
| 27 | + try { |
| 28 | + random = SecureRandom.getInstanceStrong(); // Strong cryptographic random number generator |
| 29 | + } catch (NoSuchAlgorithmException e) { |
| 30 | + random = new SecureRandom(); |
| 31 | + } |
| 32 | + |
| 33 | + StringBuilder password = new StringBuilder(length); |
| 34 | + for (int i = 0; i < length; i++) { |
| 35 | + int randomIndex = random.nextInt(characters.length()); |
| 36 | + password.append(characters.charAt(randomIndex)); |
| 37 | + } |
| 38 | + |
| 39 | + return password.toString(); |
| 40 | + } |
| 41 | + |
| 42 | + public static void main(String[] args) { |
| 43 | + int length = 12; // Change the desired password length |
| 44 | + boolean useUpper = true; |
| 45 | + boolean useLower = true; |
| 46 | + boolean useDigits = true; |
| 47 | + boolean useSpecial = true; |
| 48 | + |
| 49 | + String password = generatePassword(length, useUpper, useLower, useDigits, useSpecial); |
| 50 | + System.out.println("Generated Password: " + password); |
| 51 | + } |
| 52 | +} |
0 commit comments