如何有效地在Java中生成安全的随机字母数字字符串?

如何有效地在Java中生成安全的随机(或伪随机)字母数字字符串?

初始化包含所有接受的字符( CHARS_ARRAY )的数组,然后实例化SecureRandom实例,并重复调用nextInt(CHARS_ARRAY.length)以获取char数组中的随机索引。 将每个char附加到StringBuilder直到获得预期的字符数。

以下是重复问题中我的代码的略微修改版本。

 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); } } 

使用UUID :

 UUID random = UUID.randomUUID(); System.out.println( random ); 

出于什么目的 ?

为开放密钥加密算法生成公钥,并通过Base64算法将字节序列转换为字符串。

http://download.oracle.com/javase/6/docs/api/java/security/SecureRandom.html

来自Javadoc:

 SecureRandom random = new SecureRandom(); byte bytes[] = new byte[20]; random.nextBytes(bytes);