dev*_*von 18 java security algorithm performance
如何有效地在Java中生成安全的随机(或伪随机)字母数字字符串?
JB *_*zet 22
初始化包含所有接受的字符(CHARS_ARRAY)的数组,然后实例化SecureRandom实例,并nextInt(CHARS_ARRAY.length)重复调用以获取char数组中的随机索引.将每个字符附加到a,StringBuilder直到获得预期的字符数.
Nal*_*iba 10
如果您使用Apache Commons Lang,最简单的方法是
RandomStringUtils.random(20, 0, 0, true, true, null, new SecureRandom());
Run Code Online (Sandbox Code Playgroud)
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);
}
}
Run Code Online (Sandbox Code Playgroud)
String chrs = "0123456789abcdefghijklmnopqrstuvwxyz-_ABCDEFGHIJKLMNOPQRSTUVWXYZ";
SecureRandom secureRandom = SecureRandom.getInstanceStrong();
// 9 is the length of the string you want
String customTag = secureRandom.ints(9, 0, chrs.length()).mapToObj(i -> chrs.charAt(i))
.collect(StringBuilder::new, StringBuilder::append, StringBuilder::append).toString();
System.out.println(customTag);
Run Code Online (Sandbox Code Playgroud)
例子:
// q3HX6EctP
// WjRrMjQT4
// sX-Piq4DB
Run Code Online (Sandbox Code Playgroud)
使用UUID:
UUID random = UUID.randomUUID();
System.out.println( random );
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
28984 次 |
| 最近记录: |