Hashing and Salting Passwords with Spring Security 3

kamaci picture kamaci · Sep 11, 2011 · Viewed 18.6k times · Source

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

Answer

Ali picture Ali · Sep 11, 2011

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).

<bean class="org.springframework.security.authentication.encoding.Md5PasswordEncoder" id="passwordEncoder" />

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:

<bean id="passwordEncoder" class="org.springframework.security.authentication.encoding.ShaPasswordEncoder">
     <constructor-arg value="256"/>
</bean>