Generate BCrypt Hashed Passwords using Spring Security 4

September 11, 2015 | Last tested: October 2015 | 2531 views | Comments

A quick two step process to generate BCrypt hash using Spring Security Framework 4.0.2.


This password hashing system tries to thwart off-line password cracking using a computationally-intensive hashing algorithm, based on Bruce Schneier's Blowfish cipher. The work factor of the algorithm is parameterised, so it can be increased as computers get faster.


Built and tested with the following:

  • Eclipse Juno IDE
  • Apache Tomcat 7.0.47
  • JDK 1.7.0
  • Maven 3.0.4
  • Spring Security 4.0.2
    • Password Encoder : BCryptPasswordEncoder


Step 1.

Import the BCryptPasswordEncoder() Class.



Step 2.

Call it's encode() method to generate the hash. A parameter "strength" with a default value of 10 can be set when the class is instantiated, more work needs to be done to hash the password for higher values, such as new BCryptPasswordEncoder(15) is higher than new BCryptPasswordEncoder().

String password = "]]W&uX+r";
BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder(12);
String bcryptPassword = passwordEncoder.encode(password);


Note: You should expect different hash results even with the same password input. This is because Bcrypt includes salt which are generated randomly and appended to the output, this generates unique hash values even for same password inputs.

Generate several times again and you could have different result like below.



That's all!

That's how BCrypt Hashed Passwords can be generated using Spring Security 4.