2

In my project, I'm using BCryptPasswordEncoder as a way to encode my passwords. As long as I don't shut my machine off, everything works fine, however, when re-running my code, BCryptpasswordEncoder gets re-initialized as well, resetting its hash, making the matches() method not work with the passwords in my storage, which were created with the previous hash.

Here is the piece of code I am talking about:

        PasswordEncoder encoder = new BCryptPasswordEncoder();
        User u = this.dataSource.getUserByUsername(username);
        String passwordEncoded = encoder.encode(password);
        if (u == null) {
            return "No such user";
        } else {
            if (encoder.matches(password, u.getPassword())) {
                return passwordEncoded;
            } else {
                return "Incorrect password";
            }
        }

I know that keeping a consistent hash would defeat the purpose of encoding in general, but the way it is now, shutting anything off renders all my previous user entries in my repository useless. Is there anything I can about this?

velikiy
  • 23
  • 3
  • 1
    Does this answer your question? [Why BCryptPasswordEncoder from Spring generate different outputs for same input?](https://stackoverflow.com/questions/25844419/why-bcryptpasswordencoder-from-spring-generate-different-outputs-for-same-input) – Spectric Dec 01 '20 at 21:09

1 Answers1

1

BCryptpasswordEncoder automatically salts the passwords. The specific salt that they append to the password is randomly generated every time it is initialized.

When you reinitialize BCryptpasswordEncoder, you are generating a new salt to append to the password, so naturally, the results would be different.

You can find out how to overcome this problem here

Spectric
  • 30,714
  • 6
  • 20
  • 43
  • After reading through the resource you provided, I realized that the encoder did not work in the way I thought it did and that the error was on my part, as I encrypted the users password elsewhere as well, making it double-encrypted. Thank you for your swift answer and help! – velikiy Dec 01 '20 at 21:30
  • @velikiy Glad to help :) – Spectric Dec 01 '20 at 21:31