Random Password Generator in Java

I needed a random password generator done in Java and while reading a few articles here and there I did not find the solution I was looking for. Piecing a few of them I came up with some code.

One of the requirement that made this a bit more complicated is that I needed to have a special character in the password but from a limited list of possible special characters.
I also needed to make sure that it respected some basic complexity rules.

It has a dependency on the commons-lang 3 library from Apache but since I already had it in my project it was easy to accommodate.

Maven dependency:

<dependency>
	<groupId>org.apache.commons</groupId>
	<artifactId>commons-lang3</artifactId>
	<version>3.3.1</version>
</dependency>

Java code:

package com.halogensoftware.hosting.example;

import org.apache.commons.lang3.RandomStringUtils;

public class Random {

	public static void main(String args[]){
		String pwd = "";
		for ( int i = 0; i < 1000; i++ ) {
			do {
				pwd = RandomStringUtils.random(12, "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ01234567890%#^*:");
			} while (!valid(pwd));
			System.out.println(i + ".valid pwd: " + pwd);
		}
	}

	private static boolean valid(String pwd){
		return (pwd.matches(".*([0-9]).*") && pwd.matches(".*([a-z]).*") && pwd.matches(".*([A-Z]).*") && pwd.matches(".*([%#^*:]).*"));
	}
}
Advertisements

Published by

m5c

Java developper that loves photography and good coffee

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

w

Connecting to %s