我一直在寻找一种简单的Java算法来生成伪随机字母数字字符串。在我的情况下,它将被用作唯一的会话/密钥标识符,“很可能”在超过50万代的时间内是唯一的(我的需求实际上不需要更复杂的东西)。
理想情况下,我可以根据我的独特性需求指定长度。例如,生成的长度为12的字符串可能看起来像“AEYGF7K0DM1X”。
我一直在寻找一种简单的Java算法来生成伪随机字母数字字符串。在我的情况下,它将被用作唯一的会话/密钥标识符,“很可能”在超过50万代的时间内是唯一的(我的需求实际上不需要更复杂的东西)。
理想情况下,我可以根据我的独特性需求指定长度。例如,生成的长度为12的字符串可能看起来像“AEYGF7K0DM1X”。
当前回答
public static String getRandomString(int length) {
char[] chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRST".toCharArray();
StringBuilder sb = new StringBuilder();
Random random = new Random();
for (int i = 0; i < length; i++) {
char c = chars[random.nextInt(chars.length)];
sb.append(c);
}
String randomStr = sb.toString();
return randomStr;
}
其他回答
在前面的答案中有很多StringBuilder的用法。我想这很简单,但它需要每个字符调用一个函数,增加一个数组,等等。。。
如果使用字符串生成器,建议指定字符串所需的容量,即。,
new StringBuilder(int capacity);
这是一个不使用StringBuilder或字符串附加的版本,也没有字典。
public static String randomString(int length)
{
SecureRandom random = new SecureRandom();
char[] chars = new char[length];
for(int i=0; i<chars.length; i++)
{
int v = random.nextInt(10 + 26 + 26);
char c;
if (v < 10)
{
c = (char)('0' + v);
}
else if (v < 36)
{
c = (char)('a' - 10 + v);
}
else
{
c = (char)('A' - 36 + v);
}
chars[i] = c;
}
return new String(chars);
}
使用UUID是不安全的,因为UUID的一部分根本不是随机的。erickson的过程非常简单,但它不会创建相同长度的字符串。以下代码片段应该足够了:
/*
* The random generator used by this class to create random keys.
* In a holder class to defer initialization until needed.
*/
private static class RandomHolder {
static final Random random = new SecureRandom();
public static String randomKey(int length) {
return String.format("%"+length+"s", new BigInteger(length*5/*base 32,2^5*/, random)
.toString(32)).replace('\u0020', '0');
}
}
为什么选择长度*5?让我们假设一个长度为1的随机字符串的简单情况,即一个随机字符。要获得包含所有数字0-9和字符a-z的随机字符,我们需要一个介于0和35之间的随机数来获得每个字符中的一个。
BigInteger提供了一个构造函数来生成一个随机数,均匀分布在0到(2^numBits-1)的范围内。不幸的是,35不是一个可以由2^numBits-1接收的数字。
所以我们有两个选择:要么选择2^5-1=31,要么选择2^ 6-1=63。如果我们选择2^6,我们会得到很多“不必要”/“更长”的数字。因此,2^5是更好的选择,即使我们丢失了四个字符(w-z)。现在要生成特定长度的字符串,我们可以简单地使用2^(length*numBits)-1数字。最后一个问题是,如果我们想要一个具有一定长度的字符串,随机可能会生成一个小数字,因此长度不符合要求,因此我们必须将字符串填充到所需的长度,并加上前缀零。
public static String RandomAlphanum(int length)
{
String charstring = "abcdefghijklmnopqrstuvwxyz0123456789";
String randalphanum = "";
double randroll;
String randchar;
for (double i = 0; i < length; i++)
{
randroll = Math.random();
randchar = "";
for (int j = 1; j <= 35; j++)
{
if (randroll <= (1.0 / 36.0 * j))
{
randchar = Character.toString(charstring.charAt(j - 1));
break;
}
}
randalphanum += randchar;
}
return randalphanum;
}
我使用Math.random()使用了一个非常原始的算法。为了增加随机性,可以直接实现util.Date类。尽管如此,它还是有效的。
我开发了一个应用程序,为我的项目开发一个自动生成的字母数字字符串。在这个字符串中,前三个字符是字母,后七个字符是整数。
public class AlphaNumericGenerator {
public static void main(String[] args) {
java.util.Random r = new java.util.Random();
int i = 1, n = 0;
char c;
String str = "";
for (int t = 0; t < 3; t++) {
while (true) {
i = r.nextInt(10);
if (i > 5 && i < 10) {
if (i == 9) {
i = 90;
n = 90;
break;
}
if (i != 90) {
n = i * 10 + r.nextInt(10);
while (n < 65) {
n = i * 10 + r.nextInt(10);
}
}
break;
}
}
c = (char)n;
str = String.valueOf(c) + str;
}
while(true){
i = r.nextInt(10000000);
if(i > 999999)
break;
}
str = str + i;
System.out.println(str);
}
}
另一个解决方案。。。
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();
}