Jul 192017

ADM

How to generate a random password in Java

  • 19 July 2017
  • ADM

 

 

 

How to generate a random password in Java - images/logos/java.jpg

 

Here is a simple algorithm that I am using to generate random passwords in Java. For online password generator check the password generator.

The code is based on a dictionary of characters, numbers and specials characters.

Code

package com.admfactory.basic;

import java.security.SecureRandom;

public class PasswordGenerator {

    private static SecureRandom random = new SecureRandom();

    /** different dictionaries used */
    private static final String ALPHA_CAPS = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
    private static final String ALPHA = "abcdefghijklmnopqrstuvwxyz";
    private static final String NUMERIC = "0123456789";
    private static final String SPECIAL_CHARS = "!@#$%^&*_=+-/";

    /**
     * Method will generate random string based on the parameters
     * 
     * @param len
     *            the length of the random string
     * @param dic
     *            the dictionary used to generate the password
     * @return the random password
     */
    public static String generatePassword(int len, String dic) {
	String result = "";
	for (int i = 0; i < len; i++) {
	    int index = random.nextInt(dic.length());
	    result += dic.charAt(index);
	}
	return result;
    }

    public static void main(String[] args) {
	System.out.println("Password Generator Examples");
	System.out.println();

	int len = 10;
	System.out.println("Alphanumeric password, length " + len + " chars: ");
	String password = generatePassword(len, ALPHA_CAPS + ALPHA);
	System.out.println(password);
	System.out.println();

	len = 20;
	System.out.println("Alphanumeric + special password, length " + len + " chars: ");
	password = generatePassword(len, ALPHA_CAPS + ALPHA + SPECIAL_CHARS);
	System.out.println(password);
	System.out.println();

	len = 15;
	System.out.println("Alphanumeric + numeric + special password, length " + len + " chars: ");
	password = generatePassword(len, ALPHA_CAPS + ALPHA + SPECIAL_CHARS + NUMERIC);
	System.out.println(password);
	System.out.println();
    }
}

The code is easy to be changed in order to extend the dictionary or to changed how the random characters are chosen.

Output

Password Generator Examples

Alphanumeric password, length 10 chars: 
ZkxOwwFWGU

Alphanumeric + special password, length 20 chars: 
Q/pCssbxNw@q+zQ@rXh%

Alphanumeric + numeric + special password, length 15 chars: 
oo!2gtd8WP4KG$*

 

 

 

References