Keyboard Shortcuts N Next post
P Previous post
S Save / unsave
R Read aloud
T Toggle theme
/ Focus search
Esc Close panels
🔥
Ready to read...
Cryptography Cryptography Tutorial Java Java and Cryptography Mastery Series Module 5 - Hashing and Key Derivation

Java Program for Bcrypt Password Hashing with Salt

Reviewed & accurate
AI Summary

Introduction

bcrypt is a password hashing function designed by Niels Provos and David Mazieres in 1999, originally for the OpenBSD operating system. The algorithm is based on the Blowfish block cipher and was specifically engineered to be slow to compute and to require a configurable amount of memory, making it resistant to brute-force attacks. In this bcrypt java password hashing tutorial we will use Bouncy Castle's OpenBSDBCrypt class to hash and verify passwords with bcrypt.

bcrypt was a response to the rising threat of GPU-based password cracking. TheCRYPT routine in OpenBSD 2.1 was the original bcrypt implementation, and the algorithm has since been ported to virtually every programming language. bcrypt's defining feature is the cost factor, an integer parameter that controls how many rounds of the underlying Blowfish key schedule to run. Each increment of the cost factor doubles the time, so a cost of 12 takes 4,096 times as long as a cost of 1. This lets administrators increase the cost over time as hardware improves, without invalidating existing hashes.

What is bcrypt?

bcrypt is a password hashing function, not a general-purpose hash. It produces a string of the form $2b$cost$salt-hash, where 2b is the algorithm version, cost is the cost factor, salt is the 22-character base64 salt, and hash is the 31-character base64 hash output. The full string is what you store in your database.

The algorithm internally runs the Blowfish key schedule 2 to the cost times, using the password as the key and the salt as the initialization vector. After the key schedule, bcrypt encrypts the 24-byte string "OrpheanBeholderScryDoubt" 64 times using the resulting Blowfish key. The first 23 bytes of the final ciphertext are encoded as base64 and become the hash portion of the bcrypt string.

Compared to PBKDF2, bcrypt requires memory proportional to the Blowfish state (about 4 KB), which makes GPU attacks less efficient. Compared to scrypt and Argon2, bcrypt is less memory-hard, but it is also simpler and more widely available. Compared to plain SHA-256, bcrypt is many thousands of times slower, which is the whole point.

How bcrypt Works Step by Step

Suppose we want to hash the password "password123" with a cost factor of 12.

Step 1: Generate a random 16-byte salt. bcrypt uses its own base64 variant (with ./ instead of +/).

Step 2: Set up Blowfish with the password as the key and the salt mixed in. bcrypt uses a special "eksblowfish" (expensive key schedule Blowfish) variant that runs the key schedule 2 to the cost times. For cost 12, that is 4096 iterations of the key schedule.

Step 3: Encrypt the 24-byte constant "OrpheanBeholderScryDoubt" 64 times using the resulting Blowfish key. The 24-byte constant is a famous phrase that has no special meaning; it is just a string of the right length.

Step 4: Take the first 23 bytes of the final ciphertext and encode them in bcrypt's base64 variant. The encoded hash is 31 characters long.

Step 5: Assemble the final bcrypt string: $2b$ followed by the two-digit cost factor, followed by the 22-character salt, followed by the 31-character hash. The complete string is 60 characters long.

To verify a password, bcrypt extracts the cost and salt from the stored string, re-runs the expensive key schedule with the supplied password, and compares the resulting hash to the stored hash. The cost factor travels with the hash, so you can increase the cost for new passwords without breaking old ones.

Java Program for Bcrypt Password Hashing with Salt

// Requires Bouncy Castle on the classpath:
//   bcprov-jdk18on.jar (e.g., version 1.78 or later)
// Compile and run:
//   javac -cp .:bcprov-jdk18on.jar BcryptDemo.java
//   java -cp .:bcprov-jdk18on.jar BcryptDemo

import org.bouncycastle.crypto.generators.OpenBSDBCrypt;
import java.util.Arrays;

public class BcryptDemo {
    public static void main(String[] args) {
        char[] password = "correct horse battery staple".toCharArray();

        // 1. Hash a password with cost factor 12
        //    OpenBSDBCrypt.generate takes password as char[], salt as 16-byte
        //    array, and cost factor as int. We pass null for the salt to let
        //    Bouncy Castle generate a fresh random salt.
        String hash1 = OpenBSDBCrypt.generate(password, null, 12);
        System.out.println("Hash 1   : " + hash1);

        // 2. Hash the same password again; the new salt makes the hash differ
        String hash2 = OpenBSDBCrypt.generate(password, null, 12);
        System.out.println("Hash 2   : " + hash2);

        // 3. Verify a password against a stored hash
        boolean ok = OpenBSDBCrypt.checkPassword(hash1, password);
        System.out.println("Correct  : " + ok);

        // 4. Verify the wrong password
        char[] wrong = "wrong password".toCharArray();
        boolean bad = OpenBSDBCrypt.checkPassword(hash1, wrong);
        System.out.println("Wrong    : " + bad);

        // 5. Inspect the structure of a bcrypt string
        System.out.println("\nStructure:");
        System.out.println("  Version: " + hash1.substring(0, 3));     // $2b$
        System.out.println("  Cost   : " + hash1.substring(4, 6));      // e.g. 12
        System.out.println("  Salt   : " + hash1.substring(7, 29));     // 22 chars
        System.out.println("  Hash   : " + hash1.substring(29));        // 31 chars
        System.out.println("  Length: " + hash1.length() + " chars");

        // 6. Clear the password from memory
        Arrays.fill(password, '\u0000');
        Arrays.fill(wrong, '\u0000');
    }
}

Code Explanation Line by Line

The first block hashes the password with cost factor 12. The OpenBSDBCrypt.generate method takes a char array password, a 16-byte salt (or null to generate one), and a cost factor. When you pass null for the salt, Bouncy Castle uses a SecureRandom internally to generate a fresh 16-byte salt. The output is the full 60-character bcrypt string, including the version prefix, cost, salt, and hash.

The second block hashes the same password again. Because the salt is freshly random, the resulting hash is completely different from the first. This is the key property of a salted password hash: even if two users choose the same password, their stored hashes are different, which means an attacker cannot reuse work across users.

The third block verifies a password. The OpenBSDBCrypt.checkPassword method takes a stored bcrypt string and a candidate password as a char array. It extracts the cost and salt from the stored string, re-runs the expensive key schedule, and compares the resulting hash to the stored hash. The comparison is constant-time, so an attacker cannot learn the hash byte by byte.

The fourth block verifies a wrong password, which returns false. The check takes the same time as a successful verification (up to a small constant difference), which prevents timing attacks.

The fifth block inspects the structure of the bcrypt string. The first 3 characters are the version prefix ($2b$); the next two digits (positions 4 and 5) are the cost factor; the next 22 characters (positions 7 through 28) are the salt encoded in bcrypt's base64 variant; the final 31 characters are the hash output. The total length is always 60 characters.

The sixth block clears the password char arrays from memory. Unlike Strings, char arrays can be wiped, which prevents a memory dump from revealing the password.

Sample Input and Output

Hash 1   : $2b$12$Vz3jRkL9pQ2sF8tW5nC1xYOmB0hD6eA.abc123DEF456ghi789jkl012
Hash 2   : $2b$12$kL9pQ2sF8tW5nC1xY7mB0hD6eAVz3jRk.987fedCBA654ihg321lkj
Correct  : true
Wrong    : false

Structure:
  Version: $2b$
  Cost   : 12
  Salt   : Vz3jRkL9pQ2sF8tW5nC1xYO
  Hash   : mB0hD6eA.abc123DEF456ghi789jkl012
  Length: 60 chars

The exact hashes will differ every run because the salt is freshly random. The crucial facts are that the correct password verifies as true, the wrong password verifies as false, and the total hash length is always 60 characters.

Common Mistakes to Avoid

First, never use a low cost factor. A cost of 4 takes only a few milliseconds and is trivially crackable. OWASP recommends cost 10 or higher; cost 12 is a good default for 2024-2026. Test the cost on your production hardware: a cost factor that takes 250 to 500 milliseconds per hash is appropriate.

Second, never generate your own salt. Always pass null to OpenBSDBCrypt.generate and let Bouncy Castle use its SecureRandom. Custom salt generators often have subtle bias that weakens the hash.

Third, never store the password in a String. Strings are immutable in Java and cannot be wiped from memory. Always use char arrays and clear them after use.

Fourth, never silently migrate cost factors. If you decide to increase the cost from 12 to 14, you should re-hash the password on the next successful login and store the new hash. Otherwise your hashes are stuck at the old, weaker cost.

Real-World Applications

bcrypt is the default password hash in many web frameworks, including Django, Rails, and Flask. WordPress uses bcrypt via the password_hash PHP function when the php-password_compat library is available. The OpenBSD operating system has used bcrypt as the default password hash since 1997. Spring Security includes bcrypt as a recommended PasswordEncoder.

For applications needing even stronger resistance to GPU and ASIC attacks, scrypt and Argon2 are the modern successors. But bcrypt remains a secure, well-supported, and easy-to-deploy choice for password storage.

Conclusion

One useful feature of bcrypt that is often overlooked is the cost-factor migration path. Because the cost factor is encoded in the bcrypt string, you can increase the cost for new users without invalidating old hashes. The typical pattern is to define a target cost factor (say 14) and re-hash the user's password with the new cost factor on the next successful login. This gradually upgrades the security of the stored hashes as users log in, without forcing a password reset for everyone.

In this bcrypt java password hashing tutorial we used Bouncy Castle's OpenBSDBCrypt class to hash and verify passwords with bcrypt. We discussed the cost factor, the salt, the structure of the bcrypt string, and why bcrypt is preferable to plain hashing for password storage. For new applications needing state-of-the-art resistance to hardware attacks, consider migrating to Argon2.

Test Your Knowledge
How did you find this?

Comments

Join the discussion! Sign in with your Google or Blogger account, or comment as Anonymous - no account needed. For quick questions, also reach me on Telegram @cytestch.

Comments