Since Spring security is highly customizable, there are multiple password encoding implementations available. Spring boot developers can choose any of those schemes on the basis of their project needs.
Let’s explore the following options one by one:
This encoder relies on the BCrypt algorithm for its results. One of the key elements for BCrypt encoder is the strength/cost factor, which is the number of iterations for hashing. Another one is the object type of secureRandom
, which is a random number.
Suppose we have the following password:
"thisispassword@123"
Here’s how we can encode it using the BCrypt encoder:
BCryptPasswordEncoder(int strength, java.security.SecureRandom random)
BCryptPasswordEncoder encoder = new BCryptPasswordEncoder(14);
String encodedPassword = encoder.encode("thisispassword@123");
The output would look something like this:
"$2b$10$2Iin8gZ5hiKWUQOc3SlpL.2d.lJ2RY2zBMbXzLjCRbK.YmQZNZSAq"
This encoder depends on the SCrypt algorithm, the output for which is a derived key which is actually a password-based key used to store in the database. Some of its key elements are:
Here’s how we can encode the password using the SCrypt encoder:
SCryptPasswordEncoder(int cpuCost, int memoryCost,
int parallelization, int keyLength,
int saltLength)
SCryptPasswordEncoder encoder = new SCryptPasswordEncoder();
String encodedPassword = encoder.encode("thisispassword@123");
The output would look something like this:
"979fa54e06fad9e15634f17cfdba815573b2e68797f89f93f9e82260e8221935c2df0e310dbc45d34977f90aa876cae915a45a6fa814653edc0d6a19b155b8a3"
This encoder depends on the PBKDF2 algorithm for its output, in which PBKDF2 stands for Password-Based Key Derivation Function 2.
The key elements are:
java.lang.CharSequence
, that’s supposed to be kept secret.Here’s how we can encode the password using the Pbkdf2 encoder:
Pbkdf2PasswordEncoder(java.lang.CharSequence secret,
int iterations,int hashWidth)
Pbkdf2PasswordEncoder encoder = new Pbkdf2PasswordEncoder("mysecret",
8000, 128);
String encodedPassword = encoder.encode("thisispassword@123");
The output would look something like this:
"Ximyn2a/5e9o50WoJQGlDQ==:0BY4m75S4uujBoWQHULykw=="
We can use any of these encoders in our Spring application, each with its own set of advantages.
Free Resources