Archive

Posts Tagged ‘key stretching’

Hashing passwords in Spring Security

July 8, 2012 1 comment

Passwords should not be stored in clear text. It is a best practice to have a one way hash created before storing it. Spring Security provides a very easy way to accomplish this. Just add a passwordEncoder to the authentication-provider in the spring security configuration.
An easy way to this in Spring 3 and later is to have the following config. This uses a SHA-256 algorithm and the username is used to salt the hash.

<authentication-manager>
 <authentication-provider user-service-ref="customUserDetailsService">
 <password-encoder hash="sha-256">
 <salt-source user-property="username"/>
 </password-encoder>
 </authentication-provider>
 </authentication-manager>

In order to use hashed passwords, it becomes necessary that we store them hashed too. In order to this in the application, we can have the SignUp class hash the passwords before storing it in the datasource. (in our case MongoDB).
Here is an excerpt from my class …

@RequestMapping(value = "/signUp", method = RequestMethod.POST)
 public String home(Locale locale, Model model, @RequestParam("username") String username, @RequestParam("password") String password, @RequestParam("firstName") String firstName, @RequestParam("lastName") String lastName) {
 MongoOperations mongoOperation = (MongoOperations)mongoTemplate;
 User user = new User(username, passwordEncoder.encodePassword(password, username), firstName, lastName);
 user.setRole(2);

 logger.debug(user.toString());
 mongoOperation.save(user, "user");
 logger.debug("Adding the user to the database");
 model.addAttribute("user", user );
 return "signUpSuccessful";
 }

The following bean is used in the mongo-config.xml class to support the signUp process.

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

Spring security provides one iteration of the hash by default. In order to provide Key Stretching we can provide more iterations by using the following config instead.

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

The authentication-manager in the security config file can be used to reference the same bean so that the same number of iterations are performed at authentication.

<authentication-manager>
 <authentication-provider user-service-ref="customUserDetailsService">
 <password-encoder ref="passwordEncoder">
 <salt-source user-property="username"/>
 </password-encoder>
 </authentication-provider>
 </authentication-manager>

References:
Spring Source Doc

Advertisements