如何在Java中高效地生成安全的随机(或伪随机)字母数字字符串?
发布于 2011-08-19 01:43:21
初始化一个包含所有可接受字符的数组(CHARS_ARRAY),然后实例化一个SecureRandom实例,并重复调用nextInt(CHARS_ARRAY.length)以获得字符数组中的随机索引。将每个字符附加到一个StringBuilder中,直到得到预期的字符数。
发布于 2020-04-03 01:30:46
如果您使用Apache Commons Lang,最简单的方法是
RandomStringUtils.random(20, 0, 0, true, true, null, new SecureRandom());发布于 2011-08-19 02:04:56
下面是我的代码在the duplicate question.中稍作修改的版本
public final class RandomString
{
/* Assign a string that contains the set of characters you allow. */
private static final String symbols = "ABCDEFGJKLMNPRSTUVWXYZ0123456789";
private final Random random = new SecureRandom();
private final char[] buf;
public RandomString(int length)
{
if (length < 1)
throw new IllegalArgumentException("length < 1: " + length);
buf = new char[length];
}
public String nextString()
{
for (int idx = 0; idx < buf.length; ++idx)
buf[idx] = symbols.charAt(random.nextInt(symbols.length()));
return new String(buf);
}
}https://stackoverflow.com/questions/7111651
复制相似问题