Skip to content

Instantly share code, notes, and snippets.

@gregorygaines
Last active April 13, 2022 18:35
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save gregorygaines/d809b68e758f5d6e5c40969f1896f756 to your computer and use it in GitHub Desktop.
Save gregorygaines/d809b68e758f5d6e5c40969f1896f756 to your computer and use it in GitHub Desktop.
Simple Java Password Generator
import java.security.SecureRandom;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
public class PasswordGenerator {
// Cryptographically strong random number generator
final SecureRandom random = new SecureRandom();
// Min password length
private static final int MIN_PASSWORD_LENGTH = 12;
// Required password chars
private static final char[][] passwordChars = {
// Uppercase chars
{'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R',
'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'},
// Lowercase chars
{'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r',
's', 't', 'u', 'v', 'w', 'x', 'y', 'z'},
// Digits
{'0', '1', '2', '3', '4', '5', '6', '7', '8', '9'},
// Special chars
{'!', '@', '#', '$', '%', '^', '&', '*'},
};
public String generateRandomPassword() {
// Password string builder
final StringBuilder passwordBuilder = new StringBuilder();
// First append password with required chars
for (char[] chars : passwordChars) {
passwordBuilder.append(chars[random.nextInt(chars.length)]);
}
// Calculate how many character we need to add for a secure password
final int charsRemaining = MIN_PASSWORD_LENGTH - passwordBuilder.length();
for (int i = 0; i < charsRemaining; i++) {
// Choose a random password char arr
char[] chars = passwordChars[random.nextInt(passwordChars.length)];
// Append a random char
passwordBuilder.append(chars[random.nextInt(chars.length)]);
}
// Shuffle password
return shuffleString(passwordBuilder.toString());
}
// Shuffle string
private static String shuffleString(String str) {
List<String> stringList = Arrays.asList(str.split(""));
Collections.shuffle(stringList);
return String.join("", stringList);
}
public static void main(String[] args) {
PasswordGenerator passwordGenerator = new PasswordGenerator();
System.out.println(passwordGenerator.generateRandomPassword());
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment