Register now and start sharing your code snippets.
-->
Generating a password in Java
Java posted about 1 year ago by marko
A simple password generator class.
1 /** 2 * Simple password generator. 3 * 4 * @author marko haapala at aktagon com 5 */ 6 public class PasswordGenerator { 7 public static final char[] HEX_CHARS = { 'a','b','c','d','e','f','g','h','0','1','2','3','4','5','6','7','8','9' }; 8 public static final char[] SECURE_CHARS = { 'a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u', 9 'v','w','x','y','z','A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P', 10 'Q','R','S','T','U','V','W','X','Y','Z','0','1','2','3','4','5','6','7','8','9','=', 11 '!','"','#','¤','%','&','/','(',')' }; 12 /** 13 * Generates an eight characters long password consisting of hexadecimal characters. 14 * 15 * @return the generated password 16 */ 17 public static String generate() { 18 return generate(HEX_CHARS, 8); 19 } 20 21 /** 22 * Generates a password consisting of hexadecimal characters. 23 * 24 * @param length of the password 25 * @return the generated password 26 */ 27 public static String generate(final int length) { 28 return generate(HEX_CHARS, length); 29 } 30 31 /** 32 * Generates a password according to the given parameters. 33 * 34 * @param characters that make up the password 35 * @param length of the password 36 * @return the generated password 37 */ 38 public static String generate(final char[] characters, final int length) { 39 RandomString randomString = new RandomString(PseudoRandom.getRandom(), characters); 40 return randomString.getString(length); 41 } 42 } 43