Java Password Generator

I am trying to create a java program that creates a password, whether lowercase, lowercase and uppercase, lowercase and uppercase and numbers, lowercase and uppercase and numbers and punctuation marks, as well as the program must create one of these passwords, the user selects and must generate a length password according to what the user chooses. I have already created password options that the user can select, and suggested he choose one. I am now fixated on how to create the types of passwords that were mentioned above. One person suggested that I use ASCII values ​​and then convert them to text. I know how to convert them to text, but it will display numbers, letters and punctuation. Is there a way that I can just generate ASCII values ​​for lowercase letters only? Also, how will I generate a password according to the length of the user that they give?

+8
java generator passwords
source share
10 answers

I use this immutable class. It uses a builder pattern.
It does not support extension.

public final class PasswordGenerator { private static final String LOWER = "abcdefghijklmnopqrstuvwxyz"; private static final String UPPER = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"; private static final String DIGITS = "0123456789"; private static final String PUNCTUATION = " !@ #$%&*()_+-=[]|,./?><"; private boolean useLower; private boolean useUpper; private boolean useDigits; private boolean usePunctuation; private PasswordGenerator() { throw new UnsupportedOperationException("Empty constructor is not supported."); } private PasswordGenerator(PasswordGeneratorBuilder builder) { this.useLower = builder.useLower; this.useUpper = builder.useUpper; this.useDigits = builder.useDigits; this.usePunctuation = builder.usePunctuation; } public static class PasswordGeneratorBuilder { private boolean useLower; private boolean useUpper; private boolean useDigits; private boolean usePunctuation; public PasswordGeneratorBuilder() { this.useLower = false; this.useUpper = false; this.useDigits = false; this.usePunctuation = false; } /** * Set true in case you would like to include lower characters * (abc...xyz). Default false. * * @param useLower true in case you would like to include lower * characters (abc...xyz). Default false. * @return the builder for chaining. */ public PasswordGeneratorBuilder useLower(boolean useLower) { this.useLower = useLower; return this; } /** * Set true in case you would like to include upper characters * (ABC...XYZ). Default false. * * @param useUpper true in case you would like to include upper * characters (ABC...XYZ). Default false. * @return the builder for chaining. */ public PasswordGeneratorBuilder useUpper(boolean useUpper) { this.useUpper = useUpper; return this; } /** * Set true in case you would like to include digit characters (123..). * Default false. * * @param useDigits true in case you would like to include digit * characters (123..). Default false. * @return the builder for chaining. */ public PasswordGeneratorBuilder useDigits(boolean useDigits) { this.useDigits = useDigits; return this; } /** * Set true in case you would like to include punctuation characters * ( !@ #..). Default false. * * @param usePunctuation true in case you would like to include * punctuation characters ( !@ #..). Default false. * @return the builder for chaining. */ public PasswordGeneratorBuilder usePunctuation(boolean usePunctuation) { this.usePunctuation = usePunctuation; return this; } /** * Get an object to use. * * @return the {@link gr.idrymavmela.business.lib.PasswordGenerator} * object. */ public PasswordGenerator build() { return new PasswordGenerator(this); } } /** * This method will generate a password depending the use* properties you * define. It will use the categories with a probability. It is not sure * that all of the defined categories will be used. * * @param length the length of the password you would like to generate. * @return a password that uses the categories you define when constructing * the object with a probability. */ public String generate(int length) { // Argument Validation. if (length <= 0) { return ""; } // Variables. StringBuilder password = new StringBuilder(length); Random random = new Random(System.nanoTime()); // Collect the categories to use. List<String> charCategories = new ArrayList<>(4); if (useLower) { charCategories.add(LOWER); } if (useUpper) { charCategories.add(UPPER); } if (useDigits) { charCategories.add(DIGITS); } if (usePunctuation) { charCategories.add(PUNCTUATION); } // Build the password. for (int i = 0; i < length; i++) { String charCategory = charCategories.get(random.nextInt(charCategories.size())); int position = random.nextInt(charCategory.length()); password.append(charCategory.charAt(position)); } return new String(password); } } 

This is an example of use,

 PasswordGenerator passwordGenerator = new PasswordGenerator.PasswordGeneratorBuilder() .useDigits(true) .useLower(true) .useUpper(true) .build(); String password = passwordGenerator.generate(8); // output ex.: lrU12fmM 75iwI90o 
+33
source share

You can use org.apache.commons.lang.RandomStringUtils to generate random text / passwords. Refer to this link for example.

+16
source share

Just in case, this is useful to someone. Single line random password generator with standard Java 8 classes based on ASCII range:

 String password = new Random().ints(10, 33, 122).collect(StringBuilder::new, StringBuilder::appendCodePoint, StringBuilder::append) .toString(); 

or

 String password = new Random().ints(10, 33, 122).mapToObj(i -> String.valueOf((char)i)).collect(Collectors.joining()); 

Here the password length is 10. Of course, you can also set it arbitrarily in a certain range. And characters from the ASCII range 33-122, which are special characters, upper and lower case numbers.

If you only need lowercase letters, you can set the range: 97-122

+4
source share

You can do it as follows:

 String lower = "abc...xyz"; String digits = "0123456789"; String punct = "!#$&..."; String ... // further characer classes 

(Pay attention to those parts ... that you must fill out yourself).

From the parameters that the user selects, you create a character string to choose from by combining the corresponding character classes.

Finally, you start the loop n times, where n is the number of characters required. In each round, you select a random character from the Line you created and add it to the result:

 StringBuilder sb = new StringBuilder(); int n = ....; // how many characters in password String set = ....; // characters to choose from for (i= 0; i < n; i++) { int k = ....; // random number between 0 and set.length()-1 inklusive sb.append(set.charAt(k)); } String result = sb.toString(); 
+3
source share

Apache community text has a pretty good alternative for generating random strings. Builder is used to build the generator, after which the generator is easy to use to generate the necessary passwords.

  // Generates a 20 code point string, using only the letters az RandomStringGenerator generator = new RandomStringGenerator.Builder() .withinRange('a', 'z').build(); String randomLetters = generator.generate(20); 

Cm.

https://commons.apache.org/proper/commons-text/javadocs/api-release/org/apache/commons/text/RandomStringGenerator.html

+2
source share

You can arbitrarily choose numbers, letters, and punctuation that have dimensions. Ansii numbers from 30 to 39, lowercase letters from 61-7A, and so on. Use ansii tables

+1
source share

If it were me, I would create character arrays ( char[] ... ) that represent the different character sets that you allow, and then in your generator method you select the appropriate character array and generate a password from that. Then the hard part creates arrays of characters ...

 public String generate(char[] validchars, int len) { char[] password = new char[len]; Random rand = new Random(System.nanoTime()); for (int i = 0; i < len; i++) { password[i] = validchars[rand.nextInt(validchars.length)]; } return new String(password); } 

Then your problem just becomes generating char [] arrays that represent the different rules that you have, and how to pass this set to the generation method.

one way to do this is to create a list of regular expression rules that match the rules that you allow, and then send each character through the rules .... and if they match the rules, add them .....

Consider a function that looks like this:

 public static final char[] getValid(final String regex, final int lastchar) { char[] potential = new char[lastchar]; // 32768 is not huge.... int size = 0; final Pattern pattern = Pattern.compile(regex); for (int c = 0; c <= lastchar; c++) { if (pattern.matcher(String.valueOf((char)c)).matches()) { potential[size++] = (char)c; } } return Arrays.copyOf(potential, size); } 

Then you can get an array of arabitic characters (lowercase only) with:

 getValid("[az]", Character.MAX_VALUE); 

Or a list of all "word" characters with:

 getValid("\\w", Character.MAX_VALUE); 

Then it becomes an example of choosing a regular expression according to your requirements and "storing" an array of valid characters that will be reused every time. (Do not generate characters every time you create a password ....)

0
source share

You can try the Java implementation of Unix "pwgen". https://github.com/antiso/pwgen-gae It contains a link to the jpwgen library implementation with the CLI in Bitbucket and a link to a deployed GAE sample.

0
source share

I made a simple program that populates an ArrayList using ASCII numbers, and then uses the SecureRandom number SecureRandom to randomly select from them in a for loop, in which you can set the number of characters you want.

 import java.security.SecureRandom; import java.util.ArrayList; import java.util.List; public class PassGen { private String str; private int randInt; private StringBuilder sb; private List<Integer> l; public PassGen() { this.l = new ArrayList<>(); this.sb = new StringBuilder(); buildPassword(); } private void buildPassword() { //Add ASCII numbers of characters commonly acceptable in passwords for (int i = 33; i < 127; i++) { l.add(i); } //Remove characters /, \, and " as they're not commonly accepted l.remove(new Integer(34)); l.remove(new Integer(47)); l.remove(new Integer(92)); /*Randomise over the ASCII numbers and append respective character values into a StringBuilder*/ for (int i = 0; i < 10; i++) { randInt = l.get(new SecureRandom().nextInt(91)); sb.append((char) randInt); } str = sb.toString(); } public String generatePassword() { return str; } } 

Hope this helps! :)

0
source share
 import java.security.SecureRandom; import java.util.Random; public class PasswordHelper { public static String generatePassword (int length) { //minimum length of 6 if (length < 4) { length = 6; } final char[] lowercase = "abcdefghijklmnopqrstuvwxyz".toCharArray(); final char[] uppercase = "ABCDEFGJKLMNPRSTUVWXYZ".toCharArray(); final char[] numbers = "0123456789".toCharArray(); final char[] symbols = "^ $?!@ #%&".toCharArray(); final char[] allAllowed = "abcdefghijklmnopqrstuvwxyzABCDEFGJKLMNPRSTUVWXYZ0123456789^ $?!@ #%&".toCharArray(); //Use cryptographically secure random number generator Random random = new SecureRandom(); StringBuilder password = new StringBuilder(); for (int i = 0; i < length-4; i++) { password.append(allAllowed[random.nextInt(allAllowed.length)]); } //Ensure password policy is met by inserting required random chars in random positions password.insert(random.nextInt(password.length()), lowercase[random.nextInt(lowercase.length)]); password.insert(random.nextInt(password.length()), uppercase[random.nextInt(uppercase.length)]); password.insert(random.nextInt(password.length()), numbers[random.nextInt(numbers.length)]); password.insert(random.nextInt(password.length()), symbols[random.nextInt(symbols.length)]); } return password.toString(); } } 
0
source share

All Articles