BCrypt is a one way salted hash function based on the Blowfish cipher. It provides several enhancements over plain text passwords (unfortunately this still happens quite often) and traditional hashing algorithms (md5). It wouldn't be accurate to say BCrypt is the best way to store passwords but it should be good enough. Algorithms such as PBKDF2 could be used as a more thoroughly tested algorithm but BCrypt is commonly used as well.
jBCrypt
is a Java implementation of BCrypt.![Crypt Blowfish Java Crypt Blowfish Java](/uploads/1/2/4/4/124424618/975739558.jpg)
(Java) Blowfish Encryption, ECB, CBC, CFB modes. Blowfish encryption. CkCrypt2 crypt = new CkCrypt2; // Attention: use 'blowfish2' for the algorithm name:.
BCrypt features
- Not plain text - Not only do plain text passwords compromise your website if the database is breached but they can also compromise other websites for the users. Unfortunately a lot of users share passwords across websites.
- One way hashing - BCrypt is a one way hash function to obfuscate the password such that it is not stored in plain text.
- Salted hashing - Generating random bytes (the salt) and combining it with the password before hashing creates unique hashes across each users password. If two users have the same password they will not have the same password hash. This is to prevent rainbow table attacks which can reverse hashed passwords using common hashing functions that do not utilize a salt.
- Logarithmic iterations - The hashing function is executed many times sequentially which can be increased exponentially known as key stretching. This is to make the function CPU intensive which makes it more secure against brute force attacks.
- Updatable iterations - As CPUs become faster so do brute force attacks. Since BCrypt stores the number of iterations as part of the hash it's possible to verify a password and then increase its strength by generating a new hash with a higher number of iterations.
jBCrypt Example Wrapper.
We will be wrapping the standard
jBCrypt
with our own methods to allow auto updating the iterations on the fly.Static Hashing Utility Class
Let's make a static utility class to handle everything for us. Ideally we will periodically update the number of iterations in this class based on the recommended intervals.
![Crypt Blowfish Java Crypt Blowfish Java](/uploads/1/2/4/4/124424618/684535068.jpg)
BCrypt Java Example with Updatable Iterations
Putting it all together.
Notice how the first and second password are the same but the hashes are different. We are also able to upgrade an older version of a BCrypt password using a low number of iterations to a higher number on the fly. In the real world the passed in
Function
would be updating the database.