Password Generator in Java


In this tutorial, you will learn how to create a password generator in Java. We will create a simple password generator and a strong password generator with a strength checker.

About Password & Password Generator

A password is a secret set of characters that is used for user authentication to get access to a computer system or an application.

A strong password is a combination of alphabets, numbers, and special characters. And it should be at least 8 characters long. The longer the password, the stronger it is.

Hackers can easily crack a weak password using brute force attacks. So, it is important to create a strong password.

The password generator program we are going to see in this tutorial will generate a strong password every time you run it.

Password generator in Java

Simple Password Generator

Let's first create a simple password generator program in Java. This will give you a basic idea and initial start of how to create a password generator in Java.

To generate a password we will need to choose random characters from a set of characters. For this, we will use the Random class.

Random class is present in java.util package. So, we need to import this package into our program. It provides methods to generate random numbers, boolean, float, double, long, and strings.

Steps to create a simple password generator in Java:

  1. Import java.util.Random package.
  2. Create a function to generate the password. This function will take the size of the password as an argument.
  3. Inside the function, create a string which is a collection of characters that can be added to the password.
  4. Now run a loop that randomly creates a number between 0 and the length of the string. And use this as an index to get a random character from the string. Add this character to the password.
  5. Finally, return the password.
Example
import java.util.Random;
import java.util.Scanner;

public class generator {
    // function to generate password
    static String generate_password(int size) {
        // collection of characters that can be used in password
        String chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890!@#$%^&*()_+-/.,<>?;':\"[]{}\\|`~";

        String password = "";
        // creating object of Random class
        Random rnd = new Random();
        // looping to generate password
        while (password.length() < size) {
            // get a random number between 0 and length of chars
            int index = (int) (rnd.nextFloat() * chars.length());
            // add character at index to password
            password += chars.charAt(index);
        }
        return password;
    }

    public static void main(String[] args){
        Scanner sc = new Scanner(System.in);
        System.out.print("Enter the size of password: ");
        int size = sc.nextInt();
        sc.close();

        // calling function to generate password
        String password = generate_password(size);
        // printing the password
        System.out.println(password);
    }
}
Enter the size of password: 8
I"~|trj%

Enter the size of password: 12
Og%AKGy%KS)z

Copy the above code and paste it into a file named generator.java. Then compile and run it.

When you run the program, it will ask you to enter the size of the password. Enter the size and press enter. It will generate a random password of the given size.


Strong Password Generator

There are a few limitations in the simple password generator program we created above. It can generate a password of any size. But you can't control what type of characters it will use.

For example, if you want to create a password that contains only alphabets, then the simple password generator program will not work. It will generate a password with a mixture of all characters.

So, let's create a strong password generator program in Java where you can control what type of characters you want to use and also the size of the password.

Steps to create a strong password generator in Java:

  1. Start with importing java.util.Random package.
  2. Now create a Java function that takes 5 parameters. The first parameter is the size of the password. The next 4 parameters are boolean values that indicate whether you want to include uppercase, lowercase, numbers, and special characters in the password.
  3. Define string variables to store upper, lower, number, and special characters.
  4. According to the boolean values, add the characters to the chars variable. Which is the string that will be used to generate the password.
  5. Now create a string variable to store the password, also create a counter variable that counts the types of characters included in the password.
  6. Now include at least one of each type of character in the password. For example, if you want to include uppercase characters, then add one uppercase character to the password.
  7. Create a loop that runs until the length of the password minus the counter variable.
  8. Inside the loop, randomly select a character from the chars variable and add it to the password.
  9. Now shuffle the password for better security.
  10. Finally, return the shuffled password.
Example
import java.util.Random;

public class generator {
    public static void main(String[] args) {
        System.out.println("Password 1: " + generate_password(8, true, true, true, true));
        System.out.println("Password 2: " + generate_password(14, true, false, true, false));
        System.out.println("Password 3: " + generate_password(20, false, true, false, true));
    }

    static String generate_password(int size, boolean upper, boolean lower, boolean number, boolean special) {
        String upper_chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
        String lower_chars = "abcdefghijklmnopqrstuvwxyz";
        String number_chars = "1234567890";
        String special_chars = "!@#$%^&*()_+-/.,<>?;':\"[]{}\\|`~";

        String chars = "";
        if (upper) {
            chars += upper_chars;
        }
        if (lower) {
            chars += lower_chars;
        }
        if (number) {
            chars += number_chars;
        }
        if (special) {
            chars += special_chars;
        }
        String password = "";
        // include at least one of each type
        int count = 0;
        if (upper) {
            password += upper_chars.charAt((int) (Math.random() * upper_chars.length()));
            count++;
        }
        if (lower) {
            password += lower_chars.charAt((int) (Math.random() * lower_chars.length()));
            count++;
        }
        if (number) {
            password += number_chars.charAt((int) (Math.random() * number_chars.length()));
            count++;
        }
        if(special){
            password += special_chars.charAt((int) (Math.random() * special_chars.length()));
            count++;
        }
        Random rnd = new Random();
        while (password.length() < size-count) {
            int index = (int) (rnd.nextFloat() * chars.length());
            password += chars.charAt(index);
        }
        // shuffle the password
        String shuffled = "";
        while (password.length() > 0) {
            int index = (int) (rnd.nextFloat() * password.length());
            shuffled += password.charAt(index);
            password = password.substring(0, index) + password.substring(index + 1);
        }
        return shuffled;
    }
}
Password 1: 9}Bq
Password 2: FCLI5SNLRP4J
Password 3: m)bo%|p?rkd\w!a]%"

Strength Checker for Password

Moving with the flow of the tutorial, let's create a program in Java to check the strength of a password.

There are many ways to check the strength of a password. We will create strength value for a password based on the following criteria:

For each criterion, we will assign a value. For example, if the password contains uppercase characters, then we will add 1 to the strength value. If the password contains lowercase characters, then we will add 1 to the strength value. And so on.

Example
import java.util.*;

public class z {

    // function to generate password
    static String password_strength(String password) {
        int strength = 0;
        if (password.length() >= 8) {
            strength += 1;
        }
        if (password.matches(".*[A-Z].*")) {
            strength += 1;
        }
        if (password.matches(".*[a-z].*")) {
            strength += 1;
        }
        if (password.matches(".*[0-9].*")) {
            strength += 1;
        }
        if (password.matches(".*[!@#$%^&*()_+-/.,<>?;':\"{}\\|`~].*")) {
            strength += 1;
        }
        if (strength == 1) {
            return "Very Weak";
        } else if (strength == 2) {
            return "Weak";
        } else if (strength == 3) {
            return "Medium";
        } else if (strength == 4) {
            return "Strong";
        } else if (strength == 5) {
            return "Very Strong";
        }
        return "Very Weak";
    }

    public static void main(String[] args){
        Scanner sc = new Scanner(System.in);
        System.out.print("Type your password: ");
        String password = sc.nextLine();
        sc.close();

        // calling function to check password strength
        System.out.println("Password Strength: " + password_strength(password));
    }
}
Type your password: 12345678
Password Strength: Very Weak

Type your password: 12345678a
Password Strength: Weak

Type your password: g32#~hs8&Ad21^7
Password Strength: Very Strong

Conclusion

Summarising the above tutorial, we have learned how to create a password generator in Java. We have also learned how to check the strength of a password in Java.

You can play with the above code to create even stronger passwords. Now i'ts your turn to create a password generator in Java.

Happy coding!😊