Unit testing of BCryptPasswordEncoder hashed password

前端 未结 2 636
傲寒
傲寒 2021-01-22 23:13

In spring 5, I am using BCryptPasswordEncoder for password hashing. My code looks like below

@Autowired
private BCryptPasswordEncoder passwordEncoder;

相关标签:
2条回答
  • 2021-01-22 23:36

    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.

    0 讨论(0)
  • 2021-01-22 23:46

    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]

    0 讨论(0)
提交回复
热议问题