0

I am trying to build a simple login form using Swing in Java. I created a Sample form with two fields.

  1. usernamefield of type TextField
  2. passfield of type PasswordField

Now I have a database and in that a login table which has following structure.

username   |  password
----------------------
   abcd    |   xyz

Also I created a connection to database. and I am able to access table data by using ResultSet. I made an object of database connection called conn. I know that password is stored in the form of char array. so when I try to match password by using following code it does not work.

if(usernamefield.getText() == conn.username && passfield.getPassword().toString == conn.password) {
system.out.println("Correct");
}else {
system.out.println("Incorrect");
}

Above code always go to else block. I also noticed that passfield.getPassword() prints the correct password while passfield.getPassword().toString prints some random characters like [C@76dab03c

How to resolve it?

BenMorel
  • 34,448
  • 50
  • 182
  • 322
Atul Kumar Verma
  • 369
  • 3
  • 8
  • 23
  • You should use .equals() to compare strings, not the == operator. http://stackoverflow.com/questions/767372/java-string-equals-versus – lazarusL Apr 03 '14 at 21:14
  • `getPassword()` [returns array of characters instead of String](http://stackoverflow.com/questions/8881291/why-is-char-preferred-over-string-for-passwords). Also even if it would return Strings, [you shouldn't compare them with `==`](http://stackoverflow.com/questions/513832/how-do-i-compare-strings-in-java). – Pshemo Apr 03 '14 at 21:15
  • I am from c/c++ background and new to Java that's why used == instead of .equals. now I have changed it and it is working correctly. I will surly look into hashing functions for password security. - thanks for suggestions – Atul Kumar Verma Apr 03 '14 at 22:53

2 Answers2

0

Use equals instead of == and it should work. Never use == on strings, it hardly ever produces the result you expect.

I think the more serious issue with your code is that you're storing passwords in plain text. That is a huge security risk. You should look into password hashing algorithms, for instance bcrypt.

BadIdeaException
  • 2,125
  • 15
  • 32
0

You must compare string with .equals(), not ==, but you're doing this wrong anyway. The password should be hashed at the database, and you should be passing what the user entered to the database and having it do the matching, via a WHERE clause using the appropriate hash function. In other words, ask the database to fetch the user row with this username and password.

user207421
  • 305,947
  • 44
  • 307
  • 483