Advertisement
Guest User

gg

a guest
Nov 20th, 2019
126
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.88 KB | None | 0 0
  1. import java.util.Random;
  2.  
  3. public class PasswordGenerator {
  4.  
  5.     private static final String CAPITAL_LETTERS =
  6.  
  7.             "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
  8.  
  9.     private static final String SMALL_LETTERS =
  10.  
  11.             "abcdefghijklmnopqrstuvwxyz";
  12.  
  13.     private static final String DIGITS = "0123456789";
  14.  
  15.     private static final String SPECIAL_CHARS =
  16.  
  17.             "~!@#$%^&*()_+=`{}[]\\|':;.,/?<>";
  18.  
  19.     private static final String ALL_CHARS =
  20.  
  21.             CAPITAL_LETTERS + SMALL_LETTERS + DIGITS + SPECIAL_CHARS;
  22.  
  23.     private static Random rnd = new Random();
  24.  
  25.    public static void main(String[] args) {
  26.  
  27.     StringBuilder password = new StringBuilder();
  28.    
  29.     for (int i=1; i<=2; i++) {
  30.  
  31.         char capitalLetter = generateChar(CAPITAL_LETTERS);
  32.  
  33.         insertAtRandomPosition(password, capitalLetter);
  34.  
  35.     }
  36.    
  37.     for (int i=1; i<=2; i++) {
  38.  
  39.         char smallLetter = generateChar(SMALL_LETTERS);
  40.  
  41.         insertAtRandomPosition(password, smallLetter);
  42.  
  43.     }
  44.    
  45.     char digit = generateChar(DIGITS);
  46.  
  47.     insertAtRandomPosition(password, digit);
  48.    
  49.     for (int i=1; i<=3; i++) {
  50.  
  51.         char specialChar = generateChar(SPECIAL_CHARS);
  52.  
  53.         insertAtRandomPosition(password, specialChar);
  54.  
  55.     }
  56.    
  57.     int count = rnd.nextInt(8);
  58.  
  59.     for (int i=1; i<=count; i++) {
  60.  
  61.         char specialChar = generateChar(ALL_CHARS);
  62.  
  63.         insertAtRandomPosition(password, specialChar);
  64.  
  65.     }
  66.  
  67.  
  68.  
  69.     System.out.println(password);
  70.  
  71. }
  72.  
  73.  
  74.  
  75. private static void insertAtRandomPosition(
  76.  
  77.         StringBuilder password, char character) {
  78.  
  79.     int randomPosition = rnd.nextInt(password.length()+1);
  80.  
  81.     password.insert(randomPosition, character);
  82.  
  83. }
  84.  
  85.  
  86.  
  87. private static char generateChar(String availableChars) {
  88.  
  89.     int randomIndex = rnd.nextInt(availableChars.length());
  90.  
  91.     char randomChar = availableChars.charAt(randomIndex);
  92.  
  93.     return randomChar;
  94.    
  95.      
  96.     }
  97. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement