Java 生成随机字符串

生成指定长度的随机字符串,可用于 nonce、验证码等场景。使用 SecureRandom 保证随机性安全:

 1private static final String SYMBOLS = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
 2
 3private static final Random RANDOM = new SecureRandom();
 4
 5/**
 6 * 获取随机字符串 Nonce Str
 7 *
 8 * @return String 随机字符串
 9 */
10public static String generateNonceStr() {
11    char[] nonceChars = new char[32];
12    for (int index = 0; index < nonceChars.length; ++index) {
13        nonceChars[index] = SYMBOLS.charAt(RANDOM.nextInt(SYMBOLS.length()));
14    }
15    return new String(nonceChars);
16}

从大小写字母和数字组成的字符集里逐个取随机字符,拼成 32 位字符串。如果需要其他长度,调整 nonceChars 的长度即可。