How can I hash passwords and salt them with Spring Security 3?
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.
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.
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.
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.
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With