In spring 5, I am using BCryptPasswordEncoder for password hashing. My code looks like below
@Autowired
private BCryptPasswordEncoder passwordEncoder;
BCryptPasswordEncoder#encode
isn't deterministic. A hash will include a random salt, so your hashedPassword
and the subsequent passwordEncoder.encode
won't match*.
Firstly, you probably shouldn't test the class itself. spring-security
has BCryptPasswordEncoderTests.java. To allow testing your use of it, use NoOpPasswordEncoder, or a similar mock.
If you really want to test BCryptPasswordEncoder
, you could change your code to use a provided SecureRandom
, and then mock that, so you can control the output of encode
in your tests.
* BCRYPT_SALT_LEN is 16 bytes, so there's a non-zero possibility that two calls use the same salt.
The user you are getting from your repository has a different password. See the org.junit.ComparisonFailure
message.
passwordEncoder.encode("myPassword")
returns $2[a$10$EulgXiN/bEwjJZc2IqRgoOyTcJWNZp0STtgY0fZv9XSIWigMHiBN2]
while your user has $2[y$12$Q3BUtijkUb.HdXsYbS9rCuaCcQE0/VdU2YC.N18uZB7jZ4/r0DSzO]