问题
My program takes user name and password authentication from user before initialising the program, so i created a button login to which i associated ActionListener as show below
login.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent event){
if(txtUserName.getText().equals("Suraj") && (txtPwd.getPassword().toString()).equals("s123")){
dispose();
TimeFrame tFrame = new TimeFrame(userName);
tFrame.setVisible(true);
tFrame.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
tFrame.setLayout(new GridLayout());
} else {
JOptionPane.showMessageDialog(null,"User name or password don't match","Acces Denied", JOptionPane.ERROR_MESSAGE);
}
Now the problem that occurs is even if i enter correct password, program displays an error mes
sage回答1:
getPassword()
returns a char[]
. The toString()
on it does not return the contents as a string as you assume.
Try new String(txtPwd.getPassword()).equals("s123")
.
However, there is a reason it is a char[]
and not a String. Try looking up the security aspect of it in the javadoc.
回答2:
Note: this should have been a comment but is way too long for this. Consider giving the upvotes to the answers in the linked thread
As already indicated by mKorbel there is a rather complete discussion in getText() vs getPassword() .
Further, read the Swing tutorial about JPasswordField
which contains a nice example on how you should compare the password (by comparing char arrays, and not by converting the char array to a String
) - small copy paste from the tutorial:
private static boolean isPasswordCorrect(char[] input) {
boolean isCorrect = true;
char[] correctPassword = { 'b', 'u', 'g', 'a', 'b', 'o', 'o' };
if (input.length != correctPassword.length) {
isCorrect = false;
} else {
isCorrect = Arrays.equals (input, correctPassword);
}
//Zero out the password.
Arrays.fill(correctPassword,'0');
return isCorrect;
}
The reason why you should compare char arrays is nicely explained by Hovercraft Full Of Eels in his answer in the linked SO question at the start of this answer.
回答3:
I had the same problem:
private void loginActionPerformed(java.awt.event.ActionEvent evt) {
char[] pass = passwordField.getPassword();
String mypass = pass.toString();
String user = (String) combo.getSelectedItem();
try {
String driver = "sun.jdbc.odbc.JdbcOdbcDriver";
Class.forName(driver);
String db = "jdbc:odbc:LoginDB";
con = DriverManager.getConnection(db);
st = con.createStatement();
String sql = "select * from Table2";
rs = st.executeQuery(sql);
while (rs.next()) {
String AdminNewID = rs.getString("AdminID");
String AdminNewPass = rs.getString("AdminPassword");
if ((user.equals(AdminNewID)) && pass.equals(AdminNewPass)) {
MyApp form = new MyApp();
form.setVisible(true);
} else {
this.res.setText(" Incorrect User Name or Password");
}
}
} catch (Exception ex) {
}
}
来源:https://stackoverflow.com/questions/9894112/jpasswordfield-returning-some-hash-code-converted-into-string-type