Search code examples
javaandroidhashbcryptsalt-cryptography

Comparing hashed passwords with salt (bcrypt) always returns false


While doing an exercise for school I was required to store passwords properly (hashed in a database) using bcrypt. When comparing them the method always returns false. My code looks like that:

Register:

String username = editTextUsername.getText().toString();
String password = editTextPassword.getText().toString();
String hashedPW = BCrypt.hashpw(password, BCrypt.gensalt());
User user = new User(username, hashedPW);
user.save();

Login:

String username = editTextUsername.getText().toString();
String enteredPassword = editTextPassword.getText().toString();

String hashedPW = BCrypt.hashpw(enteredPassword, BCrypt.gensalt());

User u = usercontroller.getUser(username); //gets user object
String password = u.getPassword;

BCrypt.checkpw(password, hashedPW); //always returns false

I hope there are any BCrypt pros out there that could possibly help me. Thank you in advance!


Solution

  • change

    BCrypt.checkpw(password, hashedPW);
    

    to

    BCrypt.checkpw(enteredPassword, password);
    

    Then it will evaluate properly .

    It's doesn't matter if password is appended with salt and hash is generated .

    Hashes of same password with different salts , when evaluated against the password from which it was generated ,will evaluate to true .

    Hashing is one way algorithm this means that We cannot recompute the password by having hash. We can only compare Password with password's Hash using hashing algorithm .Hashing algorithm typically is used to generated the Hash and to compare it with whatever it was generated from. We use Hashing to store password securely