Skip to content

BCryptPasswordEncoder#

BCryptPasswordEncoder#

  • BCriptPasswordEncoder uses a BCrypt strong hashing function to encode the password. You could instantiate the BCriptPasswordEncoder by calling the no-arguments constructor. But you can also have the option to specify a strength coefficient representing the log roughs used in the encoding process. Moreover, you can as well alter the SecureRandom instance used for encoding.

1
2
3
4
PasswordEncoder p = new BCryptPasswordEncoder();
PasswordEncoder p = new BCryptPasswordEncoder(4);
SecureRandom s = SecureRandom.getInstanceStrong();
PasswordEncoder p = new BCryptPasswordEncoder(4, s);
- So If we look into the BCriptPasswordEncoder at method encode we will see that it use a random salt. So It means every time the password is encoded so we will received a different hash string, because the salt is always change. This will make hackers can not determine the data which is hashed behind, because they always see different hash string with a same data. - Then in the method matches, the BCriptPasswordEncoder will compare the raw password (plain text) with the hashed password which is loaded from the database. So at this step, you will think that how they can compare a plain text password with a hashed password right, you don't know where is the salt, and it is the random salt also. - So actually when you use the BCriptPasswordEncoder to encode a password and received a hashed string. Actually, this hashed string also contains the random salt in the prefix of the hash. Then when the BCriptPasswordEncoder does the comparison, the raw password will be hashed again with the salt that is extracted from the existed hash string from the database. - A BCript hash will contain components as below:

1
$2<a/b/x/y>$[cost]$[22 character salt][31 character hash]
  • For the example:
1
2
3
$2a$12$R9h/cIPz0gi.URNNX3kh2OPST9/PgBkqquzi.Ss7KIUgO2t0jWMUW
\__/\/ \____________________/\_____________________________/
Alg Cost      Salt                        Hash
  • In which:
    • Alg: The hash algorithm identifier (bcrypt). $2a$ Blowfish-based crypt ('bcrypt')
    • Cost: Input cost (2^12 i.e. 4096 rounds). Cost min 4, Cost max 31.
    • Salt: R9h/cIPz0gi.URNNX3kh2O A radix-64 encoding of the input salt
    • Hash: PST9/PgBkqquzi.Ss7KIUgO2t0jWMUW A radix-64 encoding of the first 23 bytes of the computed 24 byte hash

Note: The radix-64 encoding in bcrypt uses the table ./ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789, which is different than RFC 4648 Base64 encoding.

See Also#

References#