Generate Secure Password In Java

In this short code example we will generate a random alpha-numeric string of characters which can be used as a user password.

The code example below allows you to specify the password length. Although, the longer the password is the more difficult it is to brute force it but keep in mind that the longer the password is the more difficult it is to remember it as well. In my opinion, 8-10 length password is strong enough in most of the cases. With the code example below, you can always make it a bit longer.

 

package com.appsdeveloperblog.encryption;

import java.security.SecureRandom;
import java.util.Random;
 
public class GenerateSecurePassword {

    private static final Random RANDOM = new SecureRandom();
    private static final String ALPHABET = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";

    public static void main(String[] args) {

        // Define desired password length
        int passwordLength = 10;
        
        // Generate Secure Password
        String password = generatePassword(passwordLength);
        
        // Print out password value
        System.out.println("Secure password: " + password);
    }

    public static String generatePassword(int length) {
        StringBuilder returnValue = new StringBuilder(length);

        for (int i = 0; i < length; i++) {
            returnValue.append(ALPHABET.charAt(RANDOM.nextInt(ALPHABET.length())));
        }

        return new String(returnValue);
    }
}

 

Happy coding!

 

Leave a Reply

Your email address will not be published.