Hashing and Salting Passwords with Spring Security 3

18,560

Solution 1

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>

Solution 2

Simplest seems to be Spring Security 3.1 assuming no constraints on the way hashing should be done:

<bean id="encoder" class="org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder"/>

<security:authentication-manager>
    <security:authentication-provider>
        <security:password-encoder ref="encoder"/>
        <security:jdbc-user-service data-source-ref="dataSource" users-by-username-query="select username,password, enabled from users where username=?" authorities-by-username-query="select u.username, ur.authority from users u, user_roles ur where u.username = ur.username and u.username =?"/>
    </security:authentication-provider>
</security:authentication-manager>


@Controller
@Stateless
public class UsersEJB {
    @PersistenceContext(unitName = "somePU")
    private EntityManager em;
    @Transactional
    public void create(Users users) {
        PasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
        String hashedPassword = passwordEncoder.encode(users.getPassword());
        users.setPassword(hashedPassword);
        em.persist(users);
    }
}

Solution 3

easiest way, as documented:

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

HTH

Share:
18,560
kamaci
Author by

kamaci

Updated on June 13, 2022

Comments

  • kamaci
    kamaci about 2 years

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