如何有效地在Java中生成安全的随机(或伪随机)字母数字字符串?
初始化包含所有已接受的字符(CHARS_ARRAY
)的数组,然后实例化SecureRandom实例,并重复调用nextInt(CHARS_ARRAY.length)
以获取char数组中的随机索引。将每个字符附加到StringBuilder
,直到获得预期的字符数。
这是我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);
}
}
使用UUIDs:
UUID random = UUID.randomUUID();
System.out.println( random );
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);
例子:
// q3HX6EctP
// WjRrMjQT4
// sX-Piq4DB
为开放密钥加密算法生成公钥,并通过Base64算法将字节序列转换为字符串。
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();
}
}
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);