Generating password in Java

Java Programming Java8Object Oriented Programming

Generate temporary password is now a requirement on almost every website now-a-days. In case a user forgets the password, system generates a random password adhering to password policy of the company. Following example generates a random password adhering to following conditions −

  • It should contain at least one capital case letter.

  • It should contain at least one lower-case letter.

  • It should contain at least one number.

  • Length should be 8 characters.

  • It should contain one of the following special characters: @, $, #, !.

Example

import java.util.Random;

public class Tester{
   public static void main(String[] args) {
      System.out.println(generatePassword(8));
   }

   private static char[] generatePassword(int length) {
      String capitalCaseLetters = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
      String lowerCaseLetters = "abcdefghijklmnopqrstuvwxyz";
      String specialCharacters = "!@#$";
      String numbers = "1234567890";
      String combinedChars = capitalCaseLetters + lowerCaseLetters + specialCharacters + numbers;
      Random random = new Random();
      char[] password = new char[length];

      password[0] = lowerCaseLetters.charAt(random.nextInt(lowerCaseLetters.length()));
      password[1] = capitalCaseLetters.charAt(random.nextInt(capitalCaseLetters.length()));
      password[2] = specialCharacters.charAt(random.nextInt(specialCharacters.length()));
      password[3] = numbers.charAt(random.nextInt(numbers.length()));
   
      for(int i = 4; i< length ; i++) {
         password[i] = combinedChars.charAt(random.nextInt(combinedChars.length()));
      }
      return password;
   }
}

Output

cF#0KYbY
raja
Published on 14-Aug-2018 08:05:54
Advertisements