Wednesday, August 13, 2014

Spring Security - Adding Salt to Hash

Spring security has the capability to support password hash with salt out of the box. There are two parts to this implementation, one is while creating the user and other is while authenticating the user.

Let's first see the create user part of the thing. For that we need to hash the clear text password and then add a salt to it. Salt is important to save the application from rainbow attacks. Spring comes with implementations for encoders. One of them is ShaHashcodeEncoder. Register the encoder in the context file

id="passwordEncoder" />

Now in the user creation routine, hash the password as follows:

private String generateEncryptedPassword(String clearPassword, String  salt) {
        String encodedPassword = 
        return encodedPassword;

Spring provides a salt management class also which can be used to handle the salt attribute. In that case, you need not send the salt to encodePassword method but register the salt and tell it about the attribute of UserDetails object to be used as salt.

Now, while authenticating the user, you just need to tell Spring to use the right encoding and the salt and everything falls in place.

<authentication-provider user-service-ref="<your class here>">
<password-encoder hash="sha">
<salt-source user-property="username" />

More Articles on Spring

No comments:

Post a Comment