Hashing Passwords in Java with BCrypt

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.

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.

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.