Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Hashing and Salting Passwords with Spring Security 3

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

like image 923
kamaci Avatar asked Sep 11 '11 12:09

kamaci


People also ask

Does Spring Security support password hashing?

Password Hashing With Spring Security Luckily for us, Spring Security ships with support for all these recommended algorithms via the PasswordEncoder interface: Pbkdf2PasswordEncoder gives us PBKDF2. BCryptPasswordEncoder gives us BCrypt, and. SCryptPasswordEncoder gives us SCrypt.

How do I hash a password in spring boot?

All you need to do is to start an instance of the BCryptPasswordEncoder. There are two main methods that you will need from the encoder. The encode method, which generates the hash value, and the matches method which compares a password and a bcrypt hash to figure out if the password matches the hashed value.

What is hashing and salting a password?

Hashing is a one-way process that converts a password to ciphertext using hash algorithms. A hashed password cannot be decrypted, but a hacker can try to reverse engineer it. Password salting adds random characters before or after a password prior to hashing to obfuscate the actual password.

How should passwords be stored in spring?

Instead of using just the password as input to the hash function, random bytes (known as salt) would be generated for every users' password. The salt and the user's password would be ran through the hash function which produced a unique hash. The salt would be stored alongside the user's password in clear text.


1 Answers

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>
like image 63
Ali Avatar answered Oct 20 '22 20:10

Ali