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

How to generate a secure random alphanumeric string in Java efficiently?

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


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


这是我的代码在重复问题中的一个稍微修改过的版本。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
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:

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


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
import java.security.SecureRandom;
import java.util.Random;

public class PasswordHelper {        

    public static String generatePassword (int length) {

    //minimum length of 6
    if (length < 4) {
        length = 6;
    }

    final char[] allAllowed ="abcdefghijklmnopqrstuvwxyzABCDEFGJKLMNPRSTUVWXYZ0123456789".toCharArray();

    //Use cryptographically secure random number generator
    Random random = new SecureRandom();

    StringBuilder password = new StringBuilder();

    for (int i = 0; i < length; i++) {
        password.append(allAllowed[random.nextInt(allAllowed.length)]);
    }

    return password.toString();

    }

}


1
2
3
4
5
6
    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);

示例:

1
2
3
// q3HX6EctP
// WjRrMjQT4
// sX-Piq4DB

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


http://download.oracle.com/javase/6/docs/api/java/security/securelrandom.html下载

来自JavaDoc:

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