產生隨機密碼、驗證碼、Token 時常需自訂字元集(小寫、大寫、數字、符號)。本文提供一個 PassWord 工具類,使用枚舉定義字元集組合,靈活產生指定長度的隨機字串。
import java.util.*;
public class RandomStringGenerator {
public enum CharSet {
LOWER("abcdefghijklmnopqrstuvwxyz"),
UPPER("ABCDEFGHIJKLMNOPQRSTUVWXYZ"),
DIGIT("0123456789"),
SYMBOL("~!@#$%^&*()_+-=[]{}|:;<>,.?/");
final String chars;
CharSet(String chars) { this.chars = chars; }
}
private static final Random RND = new Random();
/**
* 產生隨機字串
* @param length 長度
* @param sets 使用的字元集(可多選)
* @return 隨機字串
*/
public static String generate(int length, CharSet... sets) {
StringBuilder pool = new StringBuilder();
for (CharSet s : sets) pool.append(s.chars);
if (pool.isEmpty()) throw new IllegalArgumentException("至少需選一個字元集");
char[] result = new char[length];
for (int i = 0; i < length; i++) {
result[i] = pool.charAt(RND.nextInt(pool.length()));
}
return new String(result);
}
public static void main(String[] args) {
System.out.println(generate(16, CharSet.UPPER, CharSet.DIGIT)); // 如 A7K9...
System.out.println(generate(24, CharSet.values())); // 全字元集
}
}
// 8 碼純數字驗證碼
String otp = RandomStringGenerator.generate(6, CharSet.DIGIT);
// 12 碼強密碼(大小寫+數字+符號)
String pwd = RandomStringGenerator.generate(12, CharSet.LOWER, CharSet.UPPER, CharSet.DIGIT, CharSet.SYMBOL);
java.util.Random 非加密安全,產生密碼/Token 請改用 SecureRandom。