I am trying to implement a login page, the user is supposed to enter their name and password. These values will be compared from the SQL table and the user will be allowed to log in if they match. But here the password uses JPasswordField from Swing and on searching for the password, the SQL table provides an encrypted password like this [C@44d2e990. I am unable to compare the password as user input is in form of a string while the table gives an encrypted string of password.
JOptionPane.showMessageDialog(null, new String(passwordField.getPassword()));
PreparedStatement stmt = con.prepareStatement("select username, password from signup");
ResultSet rs = stmt.executeQuery();
while (rs.next()) {
String un = rs.getString("username");
String pwd = rs.getString("password");
JOptionPane.showMessageDialog(null,pwd);
if (un.equals(textField.getText()) && pwd.equals(new String(passwordField.getPassword()))) {
JOptionPane.showMessageDialog(null,new String(passwordField.getPassword()));
JOptionPane.showMessageDialog(null, "Login Successful..");
flag = 1;
break;
}
}
if (flag != 1) {
JOptionPane.showMessageDialog(null, "Login unsuccessful..\nTry again.");
textField.setText("");
passwordField.setText("");
}
I think the first thing you need to do is to get away from the idea that a value such as
[C@44d2e990is in any way encrypted.It's what the hash code of the character array that contained the password was at the time the array was created. There's simply no way to recover what the password in that array was at the time.
You haven't explained how the passwords ended up in your database as something like
[C@44d2e990. You have only shown us the code that queries the database when a user logs in. You will need to look into why the passwords incorrectly end up in the database as something like[C@44d2e990first. Any passwords of this form are useless and should be deleted.Once you can get the passwords into the database correctly, then I would expect the login code in your question to work, as it does appear to handle the fact that
JPasswordField.getPassword()returns a character array and not a string. However, I haven't tested it. I do note, as did the commenters, that it is inefficient. You don't need to fetch all values from the database table and compare each of them in turn with the details entered: you can get the database to find the matching row (if there is one) and then return that.Finally, if this code is for your own learning purposes and will never be used in production by other people, then you can probably do without hashing the passwords, as discussed in the comments. Certainly don't bother doing this until you can get the passwords working in plain text. If you did want to has passwords, you would need to look at cryptographic hashes such as SHA256 (not to be confused with the hash codes returned by
.hashCode()), and also consider salting the hash.