Unit testing of BCryptPasswordEncoder hashed password

前端 未结 2 635
傲寒
傲寒 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.

提交回复
热议问题