How do you generate a secure random (or pseudo-random) alphanumeric string in Java efficiently?
可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):
问题:
回答1:
Initialize an array containing all the accepted chars (CHARS_ARRAY
), then instantiate a SecureRandom instance, and call nextInt(CHARS_ARRAY.length)
repeatedly to get a random index in your char array. Append each char to a StringBuilder
until you get the expected number of chars.
回答2:
Here's a slightly modified version of my code from 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);
}
}
回答3:
Using UUIDs:
UUID random = UUID.randomUUID();
System.out.println( random );
回答4:
For what purpose ?
Generate a public key for an open-key encryption algorithm and convert the byte sequence to string via Base64 algorithm.
回答5:
http://download.oracle.com/javase/6/docs/api/java/security/SecureRandom.html
From the Javadoc:
SecureRandom random = new SecureRandom();
byte bytes[] = new byte[20];
random.nextBytes(bytes);