Spring Password Encryption

Let’s have a look how we can encrypt the user’s password before inserting into the database. Spring provides the PasswordEncoder interface which has multiple implementation. For example let’s use StandardPasswordEncoder. 
A standard PasswordEncoder implementation that uses SHA-256 hashing with 1024 iterations and a random 8-byte random salt value. It uses an additional system-wide secret value to provide additional protection.

First of all we need to define the following bean in the applicationContext.xml

<bean id="passwordEncoder" 
class="org.springframework.security.crypto.password.StandardPasswordEncoder"/>

After this we need to autowire the PasswordEncoder bean and do following:

@Service
public class UserService {

    @Autowired
    private PasswordEncoder passwordEncoder;

    /**
     * 
     * @param password the password
     * @return the encoded password
     */
    public String encodePassword(final String password) {
        return passwordEncoder.encode(password);
    }
}