Hashing and Salting Passwords with Spring Security 3

前端 未结 3 899
無奈伤痛
無奈伤痛 2020-12-13 15:53

How can I hash passwords and salt them with Spring Security 3?

3条回答
  •  青春惊慌失措
    2020-12-13 16:07

    Programmatic-ally you would do it as follows:

    In your application-context.xml (defined in web.xml under contextConfigLocation) file define the bean (this example uses md5).

    
    

    Then Autowire the password encoder:

    @Autowired
    PasswordEncoder passwordEncoder;
    

    In your method or wherever you want to hash and salt.

    passwordEncoder.encodePassword("MyPasswordAsString", "mySaltAsStringOrObject");
    

    The above call should return a salted hash (as a String).

    That should do it. I'm assuming you can figure out the jar's you'll need.

    UPDATE

    It should go without saying that using MD5 is not the best idea. Ideally you should use SHA-256 at least. This can be done with the ShaPasswordEncoder.

    Replace the MD5 bean config above with:

    
         
    
    

提交回复
热议问题