summaryrefslogblamecommitdiffstats
path: root/src/main/java/org/openslx/imagemaster/util/RandomString.java
blob: a0e9419f672c28de0f23c3da528d22ac64cf7efd (plain) (tree)





























                                                                                                                               
package org.openslx.imagemaster.util;

import java.security.SecureRandom;

/**
 * Generate secure random strings
 * @author nils
 *
 */
public class RandomString {
	private static final String lettersSpecial="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890+-$%&/()=?@";
	private static final String letters="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890";
	private static final SecureRandom random = new SecureRandom();
	
	/**
	 * Generate a random string.
	 * @param length the length of the string
	 * @param specialChars whether to use special charachters or not
	 * @return the generated string
	 */
	public static String generate(int length, boolean specialChars) {
		String used = (specialChars)? lettersSpecial : letters;
		String result = "";
		for (int i = 0; i < length; i++) {
			int index = (int)(random.nextDouble()*used.length());
			result += used.substring( index, index + 1 );
		}
		return result;
	}
}