java

How to generate a password with Java

When a new user is created, it is useful to generate a random password and suggest it to the user. Creating a password generator in Java is a matter of a few lines.
 

Random alphanumeric password

In Java it is quite easy to generate random numbers, which is the basis for a random password. In the following method createPassword(int length) a random position of the string is accessed until the required length is reached. Since a string is internally represented by a char array, accessing the character at a certain position is a rather simple operation:

public static String createPassword(int length)
{
    final String allowedChars = "abcdefghijklmnopqrstuvwABCDEFGHIJKLMNOP0123456789!§$%&?*+#";
    SecureRandom random = new SecureRandom();
    StringBuilder pass = new StringBuilder(length);
    
    for (int i = 0; i < length; i++) 
    {
        pass.append(allowedChars.charAt(random.nextInt(allowedChars.length())));
    }
    
    return pass.toString();
}
[st_adsense]  
The string allowedChars can of course also be stored in a static final variable (constant) or read from a configuration. To keep the overview it should remain hardcoded in the method itself in this example. The Java Virtual Machine will create the variable only once and not as you might think at every method call.

In order to actually generate non-reproducible random numbers, the java.security.SecureRandom class is used here instead of the java.util.Random class. In the Javadoc you can read why this is the case;).
 

Random numeric password (for example PIN code)

Creating a numeric password is even easier because you don’t need a set of allowed chars. The nextInt() method delivers a numerical value anyway.

public static String generatePin(int length)
{
    SecureRandom rand = new SecureRandom();
    StringBuilder password = new StringBuilder(length);
    
    for (int i = 0; i < length; i++) 
    {
        password.append(rand.nextInt(10));
    }
    
    return password.toString();
}

The principle is the same as above: an empty StringBuilder is created and then random numbers are added one by one until the desired length is reached.
 
[st_adsense] java-mcq-multiple-choice-questions-and-answersJava MCQ – Multiple Choice Questions and Answers – OOPsThis collection of Java Multiple Choice Questions and Answers (MCQs): Quizzes & Practice Tests with Answer focuses on “Java OOPs”.   1. Which of the…Read More mcqMCQPractice competitive and technical Multiple Choice Questions and Answers (MCQs) with simple and logical explanations to prepare for tests and interviews.Read More

Leave a Reply

Your email address will not be published. Required fields are marked *