How to generate random passwords in Java?

Category: Java, Random String Generation

Generating random passwords is now much easier. I, personally, have tested the randomness with 100000 generated passwords.

Prerequisite

  • Basic knowledge about Regular Expressions (RegEx).

Requirements

Code

import nl.flotsam.xeger.Xeger;
import dk.brics.automaton.Automaton;

public class RandomizePassword{
    public string generatePassword(){
        String regex = "[a-zA-Z0-9]{8}";  //change this based on your needs.
        Xeger generator = new Xeger(regex);
        String result = generator.generate();
        return result;
    }
}

Suggestions

  • Change the regex based on your needs.
  • [a-zA-Z0-9]{8}” – The number “8″ specified here is the length of the string to be generated. You can also specify upper limit and lower limit like “[a-zA-Z0-9]{6,8}” which will produce password with length ranging from 6 to 8.
  • If you do not want your generated password to contain UPPER_CASE letters, then you can use “[a-z0-9]{8}“.
  • If you need to include special characters in your generated passwords, then you can use “[a-zA-Z0-9!_@#$%&]{8}“.
  • You can also use this code to generate random random data for testing your application. The only thing you have to do is change the regex. Eg. “(20[0-9]{2})-(0[1-9]|1[0-2])-(0[1-9]|[12][0-9]|3[01])” will generate random date in the format yyyy-MM-dd.

Leave a Reply