我想每次都生成一個唯一的密碼。我正在使用此代碼來生成密碼。爲什麼我的密碼生成代碼不能按預期工作?
import java.util.Random;
public class PasswordGenerator
{
public static String generatePassword()
{
Random r[] = new Random[8];
r[0] = new Random(1234567);
r[1] = new Random(7654321);
r[2] = new Random(-1234567);
r[3] = new Random(-7654321);
r[4] = new Random(5463721);
r[5] = new Random(2743615);
r[6] = new Random(-9753214);
r[7] = new Random(-3125769);
Random x = new Random(2325671);
StringBuilder password = new StringBuilder();
int length = x.nextInt(5)+9;
password.setLength(length);
for(int i=0;i<length;i++)
{
x.setSeed(r[i%8].nextInt(500)*r[4].nextInt(900));
password.setCharAt(i,(char)(r[x.nextInt(256)%8].nextInt(95)+32));
}
return password.toString();
}
}
代碼,其中generatePassword()
被稱爲(如果它是重要的)
public void actionPerformed(ActionEvent event)
{
if(event.getSource() == generate)
{
String userName = username.getText();
if(userName.isEmpty() || username == null)
{
JOptionPane.showMessageDialog(null,"username not entered\nFirst enter your username","ERROR",JOptionPane.ERROR_MESSAGE);
username.requestFocus();
username.selectAll();
return;
}
else if(userName.length() <=5)
{
JOptionPane.showMessageDialog(null,"Bad Username.\nUsername should be atleast six characters long.","ERROR",JOptionPane.ERROR_MESSAGE);
username.requestFocus();
username.selectAll();
return;
}
else
{
String passwd = PasswordGenerator.generatePassword();
password.setText(passwd);
return;
}
}
else if(event.getSource() == submit)
{
String passwordField = password.textField();
if(passwordField.isEmpty() || passwordField == null)
{
JOptionPane.showMessageDialog(null,"Please Generate your password first by clicking on the \"Generate\" button.",JOptionPane.ERROR_MESSAGE);
generate.requestFocus();
return;
}
else
{
//do something...
}
}
}
每次生成相同的密碼,甚至當我重新編譯時間。我應該每次修改哪些內容以生成唯一密碼?
最後工作的代碼...
import java.util.Random;
public class PasswordGenerator
{
public static String generatePassword()
{
Random r[] = new Random[8];
for(int i=0;i<8;i++)
r[i] = new Random();
Random x = new Random();
StringBuilder password = new StringBuilder();
int length = x.nextInt(5)+9;
password.setLength(length);
for(int i=0;i<length;i++)
{
x.setSeed(r[i%8].nextInt(500)*r[4].nextInt(900));
password.setCharAt(i,(char)(r[x.nextInt(256)%8].nextInt(95)+32));
}
return password.toString();
}
}
特別感謝@reimeus和@喬恩飛碟雙向
好了解。感謝您的幫助,現在它正在工作。 – cyberpirate92
嗯SecureRandom ...好吧,我會記住,再次感謝 – cyberpirate92