密钥的随机字符?

时间:2011-06-17 13:45:03

标签: android

我使用以下代码为密码生成随机字符:

int randomNumber;
Random randomNumberGenerator = new Random();
randomNumber = randomNumberGenerator.nextInt(26) + 65;

if(passkey.length() != 20){
    while (passkey.length() != 20){
        passkey += (char)randomNumber; 
        randomNumber = randomNumber + 5;
    }
}

此外,在代码中,我有时会添加5或1等。

如何使随机字符为数字或字母数字而不是任何标点符号?

3 个答案:

答案 0 :(得分:3)

将要使用的字符放在字符串中,然后在字符串中选择随机位置。这样,您还可以排除容易混淆的字符,例如O0

答案 1 :(得分:1)

看看table of ASCII characters。您将看到数字对应于整数48 - 57,大写字母对应于整数65 - 90,小写字母对应于字母97 - 122(注意:所有数字都在基数10中)。

这些范围之间存在一些差距 - 即58 - 64和91 - 96.您需要更改randomNumber的计算,使其在48到122之间,同时排除这些范围。


Guffa's solution似乎更合适;我建议继续这样做。为了完整起见,我会在这里保留这个答案。

答案 2 :(得分:0)

使用以下代码

创建没有任何特殊字符的随机数

private String generateRandomID(){

            final int ID_SIZE = 16;
            final int NUM_OF_CHARS = 62;
            StringBuffer id = new StringBuffer();
            long now = new Date().getTime();

            // Set the new Seed as current timestamp
            Random r = new Random(now);

            int index = 0;
            int x = 0;

            while(x < ID_SIZE){
                  index = r.nextInt(NUM_OF_CHARS);
                  System.out.println("Index="+ index);
                  if(index < 10){
                        id.append((char)(48 + index));
                  }
                  else if(10 <= index && index <36){
                        index = index - 10;
                        id.append((char)(65 + index));
                  }else{
                        index = index - 36;
                        id.append((char)(97 + index));
                  }
                  x++;
            }

            return id.toString();
      }

由于 迪帕克

相关问题