我一直在寻找一种简单的Java算法来生成伪随机字母数字字符串。在我的情况下,它将被用作唯一的会话/密钥标识符,“很可能”在超过50万代的时间内是唯一的(我的需求实际上不需要更复杂的东西)。
理想情况下,我可以根据我的独特性需求指定长度。例如,生成的长度为12的字符串可能看起来像“AEYGF7K0DM1X”。
我一直在寻找一种简单的Java算法来生成伪随机字母数字字符串。在我的情况下,它将被用作唯一的会话/密钥标识符,“很可能”在超过50万代的时间内是唯一的(我的需求实际上不需要更复杂的东西)。
理想情况下,我可以根据我的独特性需求指定长度。例如,生成的长度为12的字符串可能看起来像“AEYGF7K0DM1X”。
当前回答
在一行中:
Long.toHexString(Double.doubleToLongBits(Math.random()));
来源:Java-生成随机字符串
其他回答
您可以为此使用Apache Commons库RandomStringUtils:
RandomStringUtils.randomAlphanumeric(20).toUpperCase();
这里有一个简单的一行代码,使用UUID作为字符基础,可以指定(几乎)任何长度。(是的,我知道以前有人建议使用UUID。)
public static String randString(int length) {
return UUID.randomUUID().toString().replace("-", "").substring(0, Math.min(length, 32)) + (length > 32 ? randString(length - 32) : "");
}
您可以在没有外部库的情况下在一行中完成此操作。
int length = 12;
String randomString = new Random().ints(48, 122).filter(i -> (i < 58 || i > 64) && (i < 91 || i > 96)).limit(length).collect(StringBuilder::new, StringBuilder::appendCodePoint, StringBuilder::append).toString();
System.out.print(randomString);
我将长度分隔成一个参数,并添加了一行以打印结果。
此代码创建一个以字母数字ascii范围为界的随机整数流。然后它过滤掉一些符号,因为字母数字范围不是连续的。然后它限制长度并将结果收集到字符串中。
因为这种方法丢弃了它生成的大约20%的数字/字符(因为它们是符号),所以对性能的影响很小。
我不觉得它特别可读,但我认为没有人在一行中提出过本机Java解决方案。
您可以创建一个包含所有字母和数字的字符数组,然后可以从该字符数组中随机选择并创建自己的字符串密码。
char[] chars = new char[62]; // Sum of letters and numbers
int i = 0;
for(char c = 'a'; c <= 'z'; c++) { // For letters
chars[i++] = c;
}
for(char c = '0'; c <= '9';c++) { // For numbers
chars[i++] = c;
}
for(char c = 'A'; c <= 'Z';c++) { // For capital letters
chars[i++] = c;
}
int numberOfCodes = 0;
String code = "";
while (numberOfCodes < 1) { // Enter how much you want to generate at one time
int numChars = 8; // Enter how many digits you want in your password
for(i = 0; i < numChars; i++) {
char c = chars[(int)(Math.random() * chars.length)];
code = code + c;
}
System.out.println("Code is:" + code);
}
另一个解决方案。。。
public static String generatePassword(int passwordLength) {
int asciiFirst = 33;
int asciiLast = 126;
Integer[] exceptions = { 34, 39, 96 };
List<Integer> exceptionsList = Arrays.asList(exceptions);
SecureRandom random = new SecureRandom();
StringBuilder builder = new StringBuilder();
for (int i=0; i<passwordLength; i++) {
int charIndex;
do {
charIndex = random.nextInt(asciiLast - asciiFirst + 1) + asciiFirst;
}
while (exceptionsList.contains(charIndex));
builder.append((char) charIndex);
}
return builder.toString();
}