RandomPasswordUtil.java

/*
 * Copyright 2018 Global Crop Diversity Trust
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.genesys.util;

import java.util.Random;

/**
 * The Class RandomPasswordUtil.
 *
 * @author Maxym Borodenko
 */
public class RandomPasswordUtil {
	private static final String symbols = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789$&@?~!%#";

	/**
	 * This method generates a random password that consists of at least one special
	 * character, one number, one lowercase letter and one uppercase letter.
	 *
	 * @param random the random
	 * @param length the password length that should be generated
	 * @return string with generated password
	 * @throws IllegalArgumentException if the 'length' parameter is lower than 4
	 * characters
	 */
	public static String generatePassword(final Random random, final int length) {
		if (length < 4) {
			throw new IllegalArgumentException("Password must be at least 4 characters");
		}
		while (true) {
			final char[] password = new char[length];
			boolean hasUpper = false, hasLower = false, hasDigit = false, hasSpecial = false;
			for (int i = 0; i < password.length; i++) {
				final char ch = symbols.charAt(random.nextInt(symbols.length()));
				if (Character.isUpperCase(ch)) {
					hasUpper = true;
				} else if (Character.isLowerCase(ch)) {
					hasLower = true;
				} else if (Character.isDigit(ch)) {
					hasDigit = true;
				} else {
					hasSpecial = true;
				}
				password[i] = ch;
			}
			if (hasUpper && hasLower && hasDigit && hasSpecial) {
				return new String(password);
			}
		}
	}
}