如何有效地在Java中生成安全的随机(或伪随机)字母数字字符串?
答案 0 :(得分:22)
初始化包含所有已接受的字符(CHARS_ARRAY
)的数组,然后实例化SecureRandom实例,并重复调用nextInt(CHARS_ARRAY.length)
以获取char数组中的随机索引。将每个字符追加到StringBuilder
,直到获得预期的字符数。
答案 1 :(得分:8)
如果您使用Apache Commons Lang,最简单的方法是
RandomStringUtils.random(20, 0, 0, true, true, null, new SecureRandom());
答案 2 :(得分:5)
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 :(得分:3)
使用UUIDs:
UUID random = UUID.randomUUID();
System.out.println( random );
答案 4 :(得分:0)
为开放密钥加密算法生成公钥,并通过Base64算法将字节序列转换为字符串。
答案 5 :(得分:0)
https://MYDOMAIN/SUBDIRECTORY/Report/ViewReportPage/reportPath=%2FGearUpAlumni%2FAlumniData&page=1&
示例:
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);
答案 6 :(得分:0)
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();
}
}
答案 7 :(得分:0)
我对此随机生成的字符串的规范是生成一个35个字符长的加密密钥(a-zA-Z2-7个字符仅用于前25个字符)。每第5个字符后使用-
,最后5个字符应为10_000到19_999之间的整数。
这是我所做的代码(在Kotlin中)。
companion object {
/**
* Letters lower & upper case excluding:
*
* - l, o, B, O
*
* Numbers excluding:
*
* - 0, 1, 8, 9
* */
val acceptedChars: CharArray
get() = charArrayOf(
'a', 'b', 'c', 'd', 'e',
'f', 'g', 'h', 'i', 'j',
'k', 'm', 'n', 'p', 'q',
'r', 's', 't', 'u', 'v',
'w', 'x', 'y', 'z', 'A',
'C', 'D', 'E', 'F', 'G',
'H', 'I', 'J', 'K', 'L',
'M', 'N', 'P', 'Q', 'R',
'S', 'T', 'U', 'V', 'W',
'X', 'Y', 'Z', '2', '3',
'4', '5', '6', '7'
)
val acceptedInts: CharArray
get() = charArrayOf(
'0', '1', '2', '3', '4',
'5', '6', '7', '8', '9'
)
fun generate(): EncryptionKey {
val random = SecureRandom()
val stringBuilder = StringBuilder()
for (i in 0 until 35) {
when (i) {
5, 11, 17, 23, 29 -> {
stringBuilder.append("-")
}
30 -> {
stringBuilder.append("1")
}
31, 32, 33, 34 -> {
val index = random.nextInt(acceptedInts.size)
stringBuilder.append(acceptedInts[index])
}
else -> {
val index = random.nextInt(acceptedChars.size)
stringBuilder.append(acceptedChars[index])
}
}
}
return EncryptionKey(stringBuilder.toString())
}
}
产生的结果:
value: 'nK6UI-DWYvu-dbmhD-KPe5X-22dPT-10027', length: '35'
value: 'NIFvi-aX4GW-3xCYV-YSAVs-tASIK-15301', length: '35'
value: 'SpNkT-qxHR7-hSMkK-hVxpp-AqLFh-19409', length: '35'
value: 'bNvi2-svqX7-cfEw5-LNYDn-C2FtW-16197', length: '35'
value: 'hhjLX-KmRQU-KbHyU-CkNyD-5ASk6-14537', length: '35'
value: 'Xd2cj-braCm-FaE4E-Jvn2G-2Dv5J-12243', length: '35'
value: '7beFb-aeSe2-iHXZe-mTUHT-aEbry-17349', length: '35'
value: 'NExMa-xCAbU-VkpyS-xeEkj-QUayd-16311', length: '35'
value: '52HWN-EX7wV-csbhj-InhtU-gbV46-18606', length: '35'
value: 'n3RTZ-whpjQ-ZjW5n-tTyfR-eLDSF-14003', length: '35'
value: 'aJEks-ccKdU-KGJdh-Rz4ck-tR7Uq-12199', length: '35'
value: 'nMcUF-ctbcy-FEfq7-VJhRx-pCKej-16369', length: '35'
答案 8 :(得分:-1)
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);