Today is Saturday, 17th June 2017

Archive for June, 2012

How to Generate a Random Password in Java

In this article, I’ll show you how to generate a random password in Java. This Java generator can be used by a website when a user forgets their password. The app will generate a new password and email it to the user. This article will simply focus on the code for generating the random password in Java. The password is randomly generated and follows these security rules:

  • at least 8 characters, max of 12
  • at least one uppercase
  • at least one lowercase
  • at least one number
  • at least one symbol @#$%=:?

Before we get into the coding of the Java implementation class, we will write a unit test. The unit test will verify that the generated password follows the security rules. In a previous post, I developed a regular expression to validate a given password. I will simply reuse that regular expression in our unit test.

@Test
public void generatePassword() {
// setup
String regex = "((?=.*\\d)(?=.*[a-z])(?=.*[A-Z])(?=.*[@#$%=:\\?]).{8,12})";
// execute
String thePassword = PasswordUtils.generatePassword();
// assert
assertNotNull(thePassword);
assertTrue(thePassword.matches(regex));
}

This test sets up the regular expression for password validation. Then we execute the method PasswordUtils.generatePassword(). Once the password is generated, then we verify this is a valid password using the regular expression.

Now let’s move on to the implementation code. We can start with a very basic implementation, that will of course fail our test. This is what we’re starting out with.

public static String generatePassword() {
return null;
}

The test fails because we assert the password is not null. That is fine, since we’re following the TDD process of “write a failing test first”. Now, we need to provide the real implementation code. In the implementation, we need to follow the rules listed above. In brief, 8-12 characters, at least one upper, one lower, one digit and one symbol @#$%=:?. So in order to accomplish this, we’ll define the valid characters/digits for each rule.

Let’s walk thru the code to see how it works. The code starts with defining a constant for the maximum length of the password. We’ll also define a random generator that we use later.

public class PasswordUtils {
/**
* Minimum length for a decent password
*/
protected static final int MAX_LENGTH = 12;
/**
* The random number generator.
*/
private static java.util.Random r = new java.util.Random();

Now, we’ll define the range of valid characters, numbers and symbols that we’ll use in the password. This is accomplished with the code below:

/**
* I, L and O are good to leave out as are numeric zero and one.
*/
private static final String DIGITS = "23456789";
private static final String LOCASE_CHARACTERS = "abcdefghjkmnpqrstuvwxyz";
private static final String UPCASE_CHARACTERS = "ABCDEFGHJKMNPQRSTUVWXYZ";
private static final String SYMBOLS = "@#$%=:?";
private static final String ALL = DIGITS + LOCASE_CHARACTERS + UPCASE_CHARACTERS + SYMBOLS;
private static final char[] upcaseArray = UPCASE_CHARACTERS.toCharArray();
private static final char[] locaseArray = LOCASE_CHARACTERS.toCharArray();
private static final char[] digitsArray = DIGITS.toCharArray();
private static final char[] symbolsArray = SYMBOLS.toCharArray();
private static final char[] allArray = ALL.toCharArray();

If you have been in the IT industry for a while, you will know that certain characters do not make good password characters. Namely, the letters “I”, “L”, and “O”. They are easily confused with their number counterparts “1” and “0” so we’ll leave them out too.

Next we’ll cover the method implementation.

/**
* Generate a random password based on security rules
*
* - at least 8 characters, max of 12
* - at least one uppercase
* - at least one lowercase
* - at least one number
* - at least one symbol
*
* @return
*/
public static String generatePassword() {
StringBuilder sb = new StringBuilder();
// get at least one lowercase letter
sb.append(locaseArray[r.nextInt(locaseArray.length)]);
// get at least one uppercase letter
sb.append(upcaseArray[r.nextInt(upcaseArray.length)]);
// get at least one digit
sb.append(digitsArray[r.nextInt(digitsArray.length)]);
// get at least one symbol
sb.append(symbolsArray[r.nextInt(symbolsArray.length)]);
// fill in remaining with random letters
for (int i = 0; i < MAX_LENGTH - 4; i++) {
sb.append(allArray[r.nextInt(allArray.length)]);
}
return sb.toString();
}

In this method, we’re building the password string using concatenation. In this case, we have the option of using StringBuffer or StringBuilder. I chose StringBuilder since it is unsynchronized and results in faster code. Now, it is just a matter of choosing a random character from each of the arrays and append it to the string. After we have the first 4 characters/digits taken care of then we fill the remaining characters with random characters from the allArray. At the end of the method, we return a string version of the password.

Here is the complete code for the class.

package com.luv2code.password.util;
/**
*
* @author Chad Darby, darby@luv2code.com
*/
public class PasswordUtils {
/**
* Minimum length for a decent password
*/
protected static final int MAX_LENGTH = 12;
/**
* The random number generator.
*/
private static java.util.Random r = new java.util.Random();
/**
* I, L and O are good to leave out as are numeric zero and one.
*/
private static final String DIGITS = "23456789";
private static final String LOCASE_CHARACTERS = "abcdefghjkmnpqrstuvwxyz";
private static final String UPCASE_CHARACTERS = "ABCDEFGHJKMNPQRSTUVWXYZ";
private static final String SYMBOLS = "@#$%=:?";
private static final String ALL = DIGITS + LOCASE_CHARACTERS + UPCASE_CHARACTERS + SYMBOLS;
private static final char[] upcaseArray = UPCASE_CHARACTERS.toCharArray();
private static final char[] locaseArray = LOCASE_CHARACTERS.toCharArray();
private static final char[] digitsArray = DIGITS.toCharArray();
private static final char[] symbolsArray = SYMBOLS.toCharArray();
private static final char[] allArray = ALL.toCharArray();
/**
* Generate a random password based on security rules
*
* - at least 8 characters, max of 12
* - at least one uppercase
* - at least one lowercase
* - at least one number
* - at least one symbol
*
* @return
*/
public static String generatePassword() {
StringBuilder sb = new StringBuilder();
// get at least one lowercase letter
sb.append(locaseArray[r.nextInt(locaseArray.length)]);
// get at least one uppercase letter
sb.append(upcaseArray[r.nextInt(upcaseArray.length)]);
// get at least one digit
sb.append(digitsArray[r.nextInt(digitsArray.length)]);
// get at least one symbol
sb.append(symbolsArray[r.nextInt(symbolsArray.length)]);
// fill in remaining with random letters
for (int i = 0; i < MAX_LENGTH - 4; i++) {
sb.append(allArray[r.nextInt(allArray.length)]);
}
return sb.toString();
}
public static void main(String[] args) {
// generate the password
String thePassword = PasswordUtils.generatePassword();
// now print it out
System.out.println("Generated password is: " + thePassword);
}
}

Now that the code is complete, we can test it using our unit test. Based on the coding, the unit test passes with flying colors, green bar!

 

The source code is available here.

I hope that you have found this article useful. Enjoy!

Share


Unit Testing a Password Utility

In this post, we are going to develop a password utility. The utility has to support password validation.

Here are the password security rules for the application:

  • at least 8 characters, max of 12
  • at least one uppercase
  • at least one lowercase
  • at least one number
  • at least one symbol @#$%=:?

In regular TDD fashion, we’ll first set out to develop unit tests that will test the functionality of the application. Based on the security rules above, we will develop unit tests for the following conditions:

  • Test for null string
  • Test for empty string
  • Test for max of 12 characters
  • Test for at least one uppercase
  • Test for at least one lowercase
  • Test for at lest one number
  • Test for at least one symbol

There a number of ways to perform the validation on the password. However, the best solution for this is a regular expression. Agreed that it takes a bit of time to develop the regular expression, but the test cases will help drive us to the correct solution.

So let’s get started with the unit tests. Based on the information above, we have the following unit tests.

package com.luv2code.password.util;
import org.junit.Test;
import static org.junit.Assert.*;
/**
*
* @author Chad Darby, darby@luv2code.com
*/
public class PasswordUtilsTest {
@Test
public void validatePassword_Null() {
// setup
String password = null;
// execute
boolean actual = PasswordUtils.validatePassword(password);
// assert
assertFalse(actual);
}
@Test
public void validatePassword_EmptyString() {
// setup
String password = "";
// execute
boolean actual = PasswordUtils.validatePassword(password);
// assert
assertFalse(actual);
}
@Test
public void validatePassword_Missing_OneNumber() {
// setup
String password = "Abcdefg#";
// execute
boolean actual = PasswordUtils.validatePassword(password);
// assert
assertFalse(actual);
}
@Test
public void validatePassword_Missing_OneUpperCaseLetter() {
// setup
String password = "abcdefg5#";
// execute
boolean actual = PasswordUtils.validatePassword(password);
// assert
assertFalse(actual);
}
@Test
public void validatePassword_Missing_OneLowerCaseLetter() {
// setup
String password = "ABCDEFG5#";
// execute
boolean actual = PasswordUtils.validatePassword(password);
// assert
assertFalse(actual);
}
@Test
public void validatePassword_Missing_OneSymbol() {
// setup
String password = "Abcdefg5";
// execute
boolean actual = PasswordUtils.validatePassword(password);
// assert
assertFalse(actual);
}
@Test
public void validatePassword_AllRulesMet() {
// setup
String password = "Abcdefg5#";
// execute
boolean actual = PasswordUtils.validatePassword(password);
// assert
assertTrue(actual);
}
@Test
public void validatePassword_LengthTooLong() {
// setup
String password = "Abcdefg5#abcdefgabcd";
// execute
boolean actual = PasswordUtils.validatePassword(password);
// assert
assertFalse(actual);
}
}

Now, we can move forward to the implementation. Essentially, we need to develop a method with the following signature:

/**
* Returns true if password matches the validation rules
*
* @param password
* @return
*/
public static boolean validatePassword(String password) {
return true;
}

Failing Tests

In true TDD fashion, this implementation will cause the majority of our tests to fail. It will fail for all invalid passwords. Our first run of the test cases will generate failures. Now, we can update the implementation to return the correct results. As I mentioned earlier, we’ll make use of a regular expression to validate the password.

package com.luv2code.password.util;
/**
*
* @author Chad Darby, darby@luv2code.com
*/
public class PasswordUtils {
private static final String VALID_PASSWORD_REGEX = "((?=.*\\d)(?=.*[a-z])(?=.*[A-Z])(?=.*[@#$%=:\\?]).{8,12})";
/**
* Returns true if password matches the validation rules
*
* @param password
* @return
*/
public static boolean validatePassword(String password) {
return (password != null && password.matches(VALID_PASSWORD_REGEX));
}
}

Passing Tests

As you can see in the validatePassword method, the conditional checks to make sure the password is not null. This supports one of the first test cases. Now, to meet the validation rules, we make use of the regular expression:

((?=.*\\d)(?=.*[a-z])(?=.*[A-Z])(?=.*[@#$%=:\\?]).{8,12})

Now, I know that looks like a really gnarly piece of gibberish, but let’s break it down one section at a time.

ExpressionDescription
(?=.*\\d)at least one digit
(?=.*[a-z])at least one lowercase
(?=.*[A-Z])at least one uppercase
(?=.*[@#$%=:\\?])at least one symbol @#$%=:?
{8,12}minimum of 8 characters, max of 12

That’s pretty much it. The regular expression is the bulk of development for this validation routine. It is nice that we were able to minimize the implementation to just a couple of lines of code. The unit tests provide coverage for the happy path, error conditions (null strings) and the edge cases.

The source code is available here.

Enjoy!

Share


How To Fix The libs.CopyLibs.classpath Problem in NetBeans 7

I recently made some updates to my NetBeans development environment and encountered this weird error:

d:\dev\myproject\nbproject\build-impl.xml:485: The libs.CopyLibs.classpath property is not set up.
This property must point to
org-netbeans-modules-java-j2seproject-copylibstask.jar file which is part
of NetBeans IDE installation and is usually located at
/java/ant/extra folder.
Either open the project in the IDE and make sure CopyLibs library
exists or setup the property manually. For example like this:
ant -Dlibs.CopyLibs.classpath=a/path/to/org-netbeans-modules-java-j2seproject-copylibstask.jar
BUILD FAILED (total time: 0 seconds)

I was able to resolve it by following these steps:

  1. In NetBeans, select Tools > Options > Miscellaneous > Ant
  2. In the Properties section, add the following property
libs.CopyLibs.classpath=pathtoyour_netbeans/java/ant/extra/org-netbeans-modules-java-j2seproject-copylibstask.jar

Click OK and Build your project again. This error will go away. Hope this helps. Happy coding!

Share