10 Practical Ways to Generate Random Passwords in Java
This article presents a collection of Java techniques—including Random, SecureRandom with Base64, ThreadLocalRandom, Collections.shuffle, third‑party libraries like Apache Commons and Guava, custom character sets, template‑based generation, and regex validation—to create secure random passwords with configurable length and complexity.
Generating random passwords in Java can be done in many ways; this guide walks through each method, explains its characteristics, and provides ready‑to‑run code examples.
1. Using java.util.Random
import java.util.Random;
public class RandomPasswordGenerator {
private static final String CHAR_LIST = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890";
private static final int LENGTH = 10;
public static void main(String[] args) {
System.out.println(generateRandomPassword());
}
public static String generateRandomPassword() {
Random random = new Random();
StringBuilder password = new StringBuilder();
for (int i = 0; i < LENGTH; i++) {
int index = random.nextInt(CHAR_LIST.length());
password.append(CHAR_LIST.charAt(index));
}
return password.toString();
}
}2. Using SecureRandom and Base64 (Java 8)
SecureRandom provides stronger randomness; Base64 encoding adds special characters.
import java.security.SecureRandom;
import java.util.Base64;
public class SecureRandomPasswordGenerator {
private static final int LENGTH = 20; // length after Base64
public static void main(String[] args) {
System.out.println(generateSecureRandomPassword());
}
public static String generateSecureRandomPassword() {
SecureRandom random = new SecureRandom();
byte[] passwordBytes = new byte[LENGTH];
random.nextBytes(passwordBytes);
String password = Base64.getEncoder().encodeToString(passwordBytes).replaceAll("=", "");
return password.substring(0, Math.min(password.length(), LENGTH));
}
}Base64 may introduce '/', '+', and '=' characters.
3. Using ThreadLocalRandom
import java.util.concurrent.ThreadLocalRandom;
public class PasswordGenerator {
private static final String CHARACTERS = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789~`!@#$%^&*()_-+={[}]|:;\"'<,>.?/";
private static final int PASSWORD_LENGTH = 12;
public static String generatePassword() {
char[] password = new char[PASSWORD_LENGTH];
for (int i = 0; i < PASSWORD_LENGTH; i++) {
int index = ThreadLocalRandom.current().nextInt(CHARACTERS.length());
password[i] = CHARACTERS.charAt(index);
}
return new String(password);
}
public static void main(String[] args) {
System.out.println(generatePassword());
}
}4. Using Collections.shuffle()
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class PasswordGenerator {
private static final String CHARACTERS = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789~`!@#$%^&*()_-+={[}]|:;\"'<,>.?/";
private static final int PASSWORD_LENGTH = 12;
public static String generatePassword() {
List<Character> charactersList = new ArrayList<>();
for (char c : CHARACTERS.toCharArray()) {
charactersList.add(c);
}
Collections.shuffle(charactersList);
StringBuilder password = new StringBuilder();
for (int i = 0; i < PASSWORD_LENGTH; i++) {
password.append(charactersList.get(i));
}
return password.toString();
}
public static void main(String[] args) {
System.out.println(generatePassword());
}
}5. Using third‑party libraries (Apache Commons Lang, Guava)
Apache Commons Lang offers RandomStringUtils for alphanumeric and ASCII characters.
import org.apache.commons.lang3.RandomStringUtils;
public class PasswordGenerator {
private static final int PASSWORD_LENGTH = 12;
public static String generatePassword() {
return RandomStringUtils.randomAlphanumeric(PASSWORD_LENGTH) +
RandomStringUtils.randomAscii(2).replaceAll("\\W", ""); // include special characters
}
public static void main(String[] args) {
System.out.println(generatePassword());
}
}6. Combining multiple character types
import java.util.Random;
public class ComplexPasswordGenerator {
private static final String UPPER_ALPHA = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
private static final String LOWER_ALPHA = "abcdefghijklmnopqrstuvwxyz";
private static final String NUMBERS = "0123456789";
private static final String SPECIAL_CHARS = "~`!@#$%^&*()_-+={[}]|:;\"'<,>.?/";
private static final int PASSWORD_LENGTH = 12;
public static String generatePassword() {
Random rand = new Random();
StringBuilder password = new StringBuilder();
// ensure at least one from each group
password.append(UPPER_ALPHA.charAt(rand.nextInt(UPPER_ALPHA.length())));
password.append(LOWER_ALPHA.charAt(rand.nextInt(LOWER_ALPHA.length())));
password.append(NUMBERS.charAt(rand.nextInt(NUMBERS.length())));
password.append(SPECIAL_CHARS.charAt(rand.nextInt(SPECIAL_CHARS.length())));
for (int i = 4; i < PASSWORD_LENGTH; i++) {
String set = getRandomCharacterSet(rand);
password.append(set.charAt(rand.nextInt(set.length())));
}
return password.toString();
}
private static String getRandomCharacterSet(Random rand) {
int idx = rand.nextInt(4);
switch (idx) {
case 0: return UPPER_ALPHA;
case 1: return LOWER_ALPHA;
case 2: return NUMBERS;
default: return SPECIAL_CHARS;
}
}
public static void main(String[] args) {
System.out.println(generatePassword());
}
}7. Using Google Guava
Guava’s CharMatcher and CharSource can generate passwords from a defined character list.
import com.google.common.base.CharMatcher;
import com.google.common.math.IntMath;
import com.google.common.collect.ImmutableList;
import java.security.SecureRandom;
import java.util.List;
public class GuavaPasswordGenerator {
private static final int PASSWORD_LENGTH = 12;
private static final String CHARACTERS = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789~`!@#$%^&*()_-+={[}]|:;\"'<,>.?/";
private static final List<Character> CHARACTER_LIST = ImmutableList.copyOf(
CHARACTERS.chars().mapToObj(c -> (char) c).collect(ImmutableList.toImmutableList()));
public static String generatePassword() {
SecureRandom random = new SecureRandom();
String password = CharMatcher.any().retainFrom(
CharSource.fromChars(CHARACTER_LIST)
.sampled(IntMath.checkedMultiply(PASSWORD_LENGTH, 4))
.retainAll(CharMatcher.anyOf(CHARACTERS))
.toString(),
PASSWORD_LENGTH);
return password;
}
public static void main(String[] args) {
System.out.println(generatePassword());
}
}8. Using Base64 encoding directly
import java.util.Base64;
import java.security.SecureRandom;
public class Base64PasswordGenerator {
private static final int BYTE_ARRAY_LENGTH = 9; // shorter byte array because Base64 expands
private static final int PASSWORD_LENGTH = 12;
public static String generatePassword() {
SecureRandom random = new SecureRandom();
byte[] randomBytes = new byte[BYTE_ARRAY_LENGTH];
random.nextBytes(randomBytes);
String base64Encoded = Base64.getEncoder().encodeToString(randomBytes);
return base64Encoded.substring(0, PASSWORD_LENGTH);
}
public static void main(String[] args) {
System.out.println(generatePassword());
}
}9. Custom character set and length
import java.security.SecureRandom;
public class CustomPasswordGenerator {
private static final String CHARACTERS = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789~`!@#$%^&*()_-+={[}]|:;\"'<,>.?/";
private static SecureRandom random = new SecureRandom();
public static String generatePassword(int length) {
if (length < 1) {
throw new IllegalArgumentException("Password length must be positive.");
}
StringBuilder password = new StringBuilder(length);
for (int i = 0; i < length; i++) {
int index = random.nextInt(CHARACTERS.length());
password.append(CHARACTERS.charAt(index));
}
return password.toString();
}
public static void main(String[] args) {
int passwordLength = 16;
System.out.println(generatePassword(passwordLength));
}
}10. Combining fixed and random characters (template)
import java.security.SecureRandom;
public class TemplateBasedPasswordGenerator {
private static final String TEMPLATE = "AbcD-####-!";
private static final String NUMBERS = "0123456789";
public static String generatePassword() {
SecureRandom secureRandom = new SecureRandom();
StringBuilder password = new StringBuilder(TEMPLATE);
for (int i = 0; i < password.length(); i++) {
char c = password.charAt(i);
if (c == '#') {
int index = secureRandom.nextInt(NUMBERS.length());
password.setCharAt(i, NUMBERS.charAt(index));
}
}
return password.toString();
}
public static void main(String[] args) {
System.out.println(generatePassword());
}
}11. Using regular expressions for validation
import java.security.SecureRandom;
import java.util.regex.Pattern;
public class RegexPasswordGenerator {
private static final String CHARACTERS = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789~`!@#$%^&*()_-+={[}]|:;\"'<,>.?/";
private static final int PASSWORD_LENGTH = 12;
private static final Pattern PASSWORD_PATTERN = Pattern.compile(
"^(?=.*[a-z])(?=.*[A-Z])(?=.*\\d)(?=.*[!@#$%^&*()_\\-+={[}\\]|:;\"'<,>.?]).{12}$");
public static String generatePassword() {
SecureRandom secureRandom = new SecureRandom();
StringBuilder password = new StringBuilder();
boolean isValid = false;
while (!isValid) {
password.setLength(0);
for (int i = 0; i < PASSWORD_LENGTH; i++) {
int index = secureRandom.nextInt(CHARACTERS.length());
password.append(CHARACTERS.charAt(index));
}
isValid = PASSWORD_PATTERN.matcher(password.toString()).matches();
}
return password.toString();
}
public static void main(String[] args) {
System.out.println(generatePassword());
}
}Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
Programmer1970
Formerly called 'Code to 35'. Add our main WeChat ID to access a wealth of shared resources (algorithms, interview prep, tech stacks: Java, Python, Go, big data). We mainly share serious development techniques, focusing on output-driven input. Occasionally we post life snippets and gossip. Our aim is to attract precise traffic and test advertising opportunities.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
