Spring Security is a powerful authentication and authorization framework. It is also highly customizable for securing Spring Boot applications.
When it comes to storing passwords, multiple password encoding implementations are provided by Spring Boot, each with its own set of strong and weak points. We can easily choose from any of them for our project. Let’s discuss how the slow hashing scheme called
BCrypt Password Encoder works in Spring Security.
First, let’s understand how the
BCrypt algorithm works.
In this algorithm, the password to be encoded goes through the following steps:
This scheme makes use of the
BCrypt algorithm discussed above. We can call it in Spring Boot like so:
// BCrypt encoder constructor BCryptPasswordEncoder(BCryptPasswordEncoder.BCryptVersion version, int strength, java.security.SecureRandom random)
We provide the following three parameters to the constructor:
version: This specifies the version of
strength: This refers to the number of iterations or log rounds it will use to compute the hash.
random: This is an object of
SecureRandomthat contains a random number used to randomize the hash that’s being calculated. This argument is optional.
Let’s encode the password
BCryptPasswordEncoder encoder = new BCryptPasswordEncoder( 16, new SecureRandom()); // 16 is the strength here String encodedPassword = encoder.encode("mypassword@4567");
We get the following result as an encoded password:
Let’s break the encoded password down to understand what it means:
＄2a＄: The hash algorithm identifier and version.
16＄: Strength or Cost factor (2^16 => 65536 rounds).
DlfkoP1HJCNbPEtgd/ITeO: 16-byte (128-bit) salt,
base64encoded to 22 characters.
jtcmUZajy9op9t21YzezT/iPY962asp: 24-byte (192-bit) hash,
base64encoded to 31 characters.
We can represent the generic form of a
BCrypt hash string like so:
$2<a/b/x/y>$[strength]$[22 character salt][31 character hash]
The biggest advantage provided by the
BCrypt password encoder is that we can easily adjust the cost of hashing. This can increase the iteration count over time, making it remarkably slow. The fact that it becomes notably time-expensive makes it almost impossible to be cracked by attackers.
View all Courses