In last Spring Security form login example, the password is stored in clear-text, it is vulnerable to attack. In practice, recommend to hash your password before storing them.

In this tutorial, we show you how to use SHA hashing algorithm to hash password, and use the hashed password to perform the login authentication in Spring Security.

To hash string with SHA or MD5 algorithm, refer to this Java SHA example or using Jacksum, third-party Java library. For readability, we will use Jacksum to perform password hashing.

1. Password

In original example, password is stored in clear text.

   <authentication-manager>
      <authentication-provider>
	<user-service>
	   <user name="mkyong" password="123456" authorities="ROLE_USER" />
	</user-service>
     </authentication-provider>
   </authentication-manager>

2. Password + Hashing

Now, use “jacksum” to hash the password “123456″ with SHA algorithm.

C:\>java -jar jacksum.jar -a sha -q "txt:123456"
7c4a8d09ca3762af61e59520943dc26494f8941b

Put above hashed password in Spring like this :

   <authentication-manager>
      <authentication-provider>
	<password-encoder hash="sha" />
	   <user-service>
	      <user name="mkyong" password="7c4a8d09ca3762af61e59520943dc26494f8941b" 
		    authorities="ROLE_USER" />
	   </user-service>
	</authentication-provider>
   </authentication-manager>

Supported hashing algorithms in Spring Security :

  1. plaintext
  2. sha
  3. sha-256
  4. md5
  5. md4
Note
MD4 is a weak hashing algorithm and MD5 is cause collision vulnerabilities, both are not recommend to use. To hash, use SHA always.

Download Source Code

References

  1. MD5 hashing algorithm
  2. SHA-1 hashing algorithm
  3. SHA-2 hashing algorithm
  4. Jacksum Java library
  5. Java SHA hashing example
  6. Spring Security form-based login example
Note : You can find more similar articles at - Spring Security Tutorials