How to store and read passwords using Bcrypt

1.5k views Asked by At

I have a problem using BCrypt. I want to store user passwords in a safe way and therefore, I am using Spring's BCrypt to store the passwords encrypted. The problem I am facing now is that BCrypt generates a random salt and of course, the password cannot be decrypted. But how can I handle a login then?

private PasswordEncoder encoder = new BCryptPasswordEncoder();

public String encryptPassword(String password) {
        String encryptedValue = encoder.encode(password);
        Assert.isTrue(encoder.matches(password, encryptedValue));
        return encryptedValue;
}

What do I need to do to make sure the passwords are matching when the user is entering his credentials?

String encryptedPassword = encryptionGenerator.encryptPassword(loginCredentials.getPassword());

And then I try to read from DB with hibernate

FROM Login WHERE email = :email AND password = :password AND email_confirmed = 1"
1

There are 1 answers

1
San On BEST ANSWER

To make sure the passwords are matching when the user is entering his credentials, No need to encode password again to validate encoded password which you got from database.

BCryptPasswordEncoder class will match password by string values only.

I tried following way and its working for me. If your concern is to authenticate a user, you can try following way:

@Autowired
UserRepository userRepository;

public void validateUser(User user) {

    // get User entity from database using your user repository
    final User currentUser = userRepository.findByEmailId(user.getUserName());

    final BCryptPasswordEncoder pwEncoder = new BCryptPasswordEncoder();
    if (pwEncoder.matches(user.getPassword(), currentUser.getPassword())) {
        // user password is correct
    }
    else{
        //user password incorrect
    }

}



public interface UserRepository extends JpaRepository<User, Long>{
        
        @Query("FROM Login WHERE emailId = :emailId")
        User findByEmailId(@param("emailId") String emailId);
    }