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.
BCrypt
algorithmFirst, let’s understand how the BCrypt
algorithm works.
In this algorithm, the password to be encoded goes through the following steps:
BCrypt
password encoderThis 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 BCrypt
.
strength
: This refers to the number of iterations or log rounds it will use to compute the hash.
random
: This is an object of SecureRandom
that contains a random number used to randomize the hash that’s being calculated. This argument is optional.BCrypt
Let’s encode the password "mypassword@4567"
:
BCryptPasswordEncoder encoder = new BCryptPasswordEncoder(16, new SecureRandom());// 16 is the strength hereString encodedPassword = encoder.encode("mypassword@4567");
We get the following result as an encoded password:
$2a$16$DlfkoP1HJCNbPEtgd/ITeOjtcmUZajy9op9t21YzezT/iPY962asp
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, base64
encoded to 22 characters.jtcmUZajy9op9t21YzezT/iPY962asp
: 24-byte (192-bit) hash, base64
encoded 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.