Search code examples
springmongodbpassword-encryption

Password encoding and decoding using Spring Security, Spring Boot and MongoDB


I use the mentions software stack above and I need to encrypt password before save into database. I also need to decrypt password because when someone will change password he she needs to give in the old password and then the new onw twice and I need to check the old password. I have searched a lot but I still not sure what is the right way to do this. I have found this link Encrypting but are there other hints to do this? I also not sure if maybe MongoDB provides something to protect passwords.


Solution

  • First read Steven Carlson´s answer about password hashing.

    The good thing is that Spring Security will do this for you. Spring Security 3.2 introduced the new org.springframework.security.crypto.password.PasswordEncoder interface and some implementations: BCryptPasswordEncoder, StandardPasswordEncoder (and NoOpPasswordEncoder).

    Important: Do not confuse org.springframework.security.crypto.password.PasswordEncoder with the old deprecated org.springframework.security.authentication.encoding.PasswordEncoder

    The interface (and therefore the implementations) has the two methods you need:

    • public String encode(CharSequence rawPassword)
    • public boolean matches(CharSequence rawPassword, String encodedPassword)

    I recommend to use org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder. The BCryptPasswordEncoder (in contrast to the StandardPasswordEncoder) use an salt that is different for each password (but not global like the one from StandardPasswordEncoder). When you encode a raw password (public String encode(CharSequence rawPassword)) then the returned encoded password is not just the encoded password, it also contains some meta information about the used hash-algorithm, the used salt and of course the encoded password.