How does the BCrypt encoding scheme work in Spring Security?

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 algorithm

First, let’s understand how the BCrypt algorithm works. In this algorithm, the password to be encoded goes through the following steps:

  • The password is first salted, which means a random sequence of characters is added to it.
  • The password is then hashed.
  • The hashing process keeps iterating itself for the specified number of rounds, called the cost factor.
BCrypt algorithm

BCrypt password encoder

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 BCrypt.
    • Values: 2a, 2b, 2x, 2y
  • strength: This refers to the number of iterations or log rounds it will use to compute the hash.
    • Range: 4 - 31
    • Default value: 10
  • 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.

Encoding password with BCrypt

Let’s encode the password "mypassword@4567":

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:

$2a$16$DlfkoP1HJCNbPEtgd/ITeOjtcmUZajy9op9t21YzezT/iPY962asp

The encoded password structure

Let’s break the encoded password down to understand what it means:

BCrypt encoded password
  • $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.

Copyright ©2024 Educative, Inc. All rights reserved