Advertisement
backrow

RandomPasswordGenerator

May 16th, 2025
136
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 2.30 KB | None | 0 0
  1. import java.util.Random;
  2.  
  3. public class RandomPasswordGenerator {
  4.     private static final String CAPITAL_LETTERS =
  5.         "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
  6.     private static final String SMALL_LETTERS =
  7.         "abcdefghijklmnopqrstuvwxyz";
  8.     private static final String DIGITS = "0123456789";
  9.     //private static final String SPECIAL_CHARS =
  10.     //    "~!@#$%^&*()_+=`{}[]\\|':;.,/?<>";
  11.     private static final String SPECIAL_CHARS =
  12.         "!@#$%&.";
  13.  
  14.     private static final String ALL_CHARS =
  15.         CAPITAL_LETTERS + SMALL_LETTERS + DIGITS + SPECIAL_CHARS;
  16.     private static Random rnd = new Random();
  17.     public static void main(String[] args) {
  18.         StringBuilder password = new StringBuilder();
  19.  
  20.         // Generate two random capital letters
  21.         for (int i=1; i<=4; i++) {
  22.             char capitalLetter = generateChar(CAPITAL_LETTERS);
  23.             insertAtRandomPosition(password, capitalLetter);
  24.         }
  25.  
  26.         // Generate two random small letters
  27.         for (int i=1; i<=4; i++) {
  28.             char smallLetter = generateChar(SMALL_LETTERS);
  29.             insertAtRandomPosition(password, smallLetter);
  30.         }
  31.  
  32.         // Generate one random digit
  33.         for (int i=1; i<=3; i++) {
  34.             char digit = generateChar(DIGITS);
  35.             insertAtRandomPosition(password, digit);
  36.             }
  37.  
  38.         // Generate 3 special characters
  39.         for (int i=1; i<=3; i++) {
  40.             char specialChar = generateChar(SPECIAL_CHARS);
  41.             insertAtRandomPosition(password, specialChar);
  42.         }
  43.  
  44.         // Generate few random characters (between 0 and 7)
  45.         int count = rnd.nextInt(8);
  46.         for (int i=1; i<=count; i++) {
  47.             char specialChar = generateChar(ALL_CHARS);
  48.             insertAtRandomPosition(password, specialChar);
  49.         }
  50.  
  51.         System.out.println(password);
  52.     }
  53.  
  54.     private static void insertAtRandomPosition(
  55.             StringBuilder password, char character) {
  56.         int randomPosition = rnd.nextInt(password.length()+1);
  57.         password.insert(randomPosition, character);
  58.     }
  59.  
  60.     private static char generateChar(String availableChars) {
  61.         int randomIndex = rnd.nextInt(availableChars.length());
  62.         char randomChar = availableChars.charAt(randomIndex);
  63.         return randomChar;
  64.     }
  65.  
  66. }
  67.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement