3 回答

TA貢獻1831條經(jīng)驗 獲得超9個贊
這是使用SecureRandom和的一種方法StringBuilder
private static String generateRandomString(int length)
{
StringBuilder sb = new StringBuilder();
SecureRandom rnd = new SecureRandom();
String uppercaseChars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
String lowercaseChars = "abcdefghijklmnopqrstuvwxyz";
String specialChars = "0123456789~`!@#$%^&*()-_=+[{]}\\\\|;:\\'\\\",<.>/?";
boolean nextIsUppercase = false;
boolean nextIsLowercase = false;
boolean nextIsSpecial = true;
for (int i = 0; i < length; i++) {
if (nextIsSpecial) {
sb.append(specialChars.charAt(rnd.nextInt(specialChars.length())));
nextIsUppercase = true;
nextIsSpecial = false;
continue;
}
if (nextIsUppercase) {
sb.append(uppercaseChars.charAt(rnd.nextInt(uppercaseChars.length())));
nextIsUppercase = false;
nextIsLowercase = true;
continue;
}
if (nextIsLowercase) {
sb.append(lowercaseChars.charAt(rnd.nextInt(lowercaseChars.length())));
nextIsLowercase = false;
nextIsSpecial = true;
continue;
}
}
return sb.toString();
}
示例輸出:
System.out.println(generateRandomString(1)); -> 7
System.out.println(generateRandomString(2)); -> :Q
System.out.println(generateRandomString(3)); -> 8St
System.out.println(generateRandomString(4)); -> =Lv%
System.out.println(generateRandomString(16)); -> %Uf-Hs<Ea|Wp;Rt}

TA貢獻1943條經(jīng)驗 獲得超7個贊
這是您問題的解決方案:
public static String GeneratePassword(int length) {
String[] characters = {"0123456789","~!@#$%^&*()-_=+[{]}|;:\'\",<.>/?","ABCDEFGHIJKLMNOPQRSTUVWXYZ","abcdefghijklmnopqrstuvwxyz"};
Random rand = new Random();
String password="";
for(int i=0;i<length;i++) {
int random = rand.nextInt(4);//choose a number from 0 to 3(inclusive)
int string_size = characters[random].length();//get length of the selected string
int random1 = rand.nextInt(string_size);//choose a number from0 to length-1 of selected string
char item = characters[random].charAt(random1);//selects the character
password=password+item;//Concatenates with the password
}
return password;
}

TA貢獻1848條經(jīng)驗 獲得超10個贊
何塞馬丁內(nèi)斯已經(jīng)提供了一個很好的方法來實現(xiàn)這是他方法的代碼片段
public static String getPassword(int length) {
assert length >= 4;
char[] password = new char[length];
//get the requirements out of the way
password[0] = LOWERCASE[rand.nextInt(LOWERCASE.length)];
password[1] = UPPERCASE[rand.nextInt(UPPERCASE.length)];
password[2] = NUMBERS[rand.nextInt(NUMBERS.length)];
password[3] = SYMBOLS[rand.nextInt(SYMBOLS.length)];
//populate rest of the password with random chars
for (int i = 4; i < length; i++) {
password[i] = ALL_CHARS[rand.nextInt(ALL_CHARS.length)];
}
//shuffle it up
for (int i = 0; i < password.length; i++) {
int randomPosition = rand.nextInt(password.length);
char temp = password[i];
password[i] = password[randomPosition];
password[randomPosition] = temp;
}
return new String(password);
}
添加回答
舉報