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 3 - Modern Symmetric Cryptography

Java Program for Blowfish Cipher with Bouncy Castle

Reviewed & accurate
AI Summary

Introduction

Blowfish is a fast, unpatented symmetric block cipher designed by the security researcher Bruce Schneier in 1993. Schneier released Blowfish into the public domain specifically to give developers a free alternative to DES, which at that time was encumbered by patent licensing. The cipher uses a 64-bit block size and accepts keys anywhere from 32 to 448 bits, which was unusually flexible for the era. In this blowfish cipher java tutorial we will use the standard javax.crypto API (which works with both the built-in SunJCE provider and Bouncy Castle) to encrypt and decrypt a message.

Although Blowfish was popular in the 1990s and still ships in many products, its 64-bit block size is now considered too small for general use. If you encrypt more than about 32 gigabytes with the same key, the birthday bound says you will start seeing block collisions that leak information. For new applications, Schneier himself recommends AES or his newer cipher Twofish, both of which use 128-bit blocks. Blowfish remains a great teaching example because the code is small and the algorithm is conceptually elegant.

What is the Blowfish Cipher?

Blowfish is a symmetric Feistel cipher with 16 rounds, just like DES, but with two important differences. First, the block size is 64 bits but the key length is variable up to 448 bits, which is huge for 1993. Second, the round function is much heavier than DES's. Instead of small 6x4 S-boxes, Blowfish uses two large S-box arrays of 1024 32-bit words each, plus an 18-entry P-array of 32-bit words. All of these arrays are initialized from the key during the Key Schedule.

This is what cryptographers call a key-dependent S-box design. The S-boxes are not fixed in hardware like DES's S-boxes; they are computed from the key itself, which makes Blowfish resistant to certain classes of analysis attacks but also makes key setup expensive. The first encryption after a key change takes much longer than subsequent ones, which is why Blowfish is excellent for applications that use one key for a long time but poor for keys that change often.

Compared to AES, Blowfish is slower in software, has a smaller block, and lacks built-in authenticated modes. Compared to DES, Blowfish has a much larger key space, no parity bits, and no NSA-designed S-boxes. Bouncy Castle supports Blowfish directly, but you can also use the built-in SunJCE provider, which has supported Blowfish since Java 1.4.

How Blowfish Works Step by Step

Blowfish's Key Schedule is the most interesting part of the algorithm. The P-array and S-boxes start with precomputed constants derived from the fractional part of pi. To set up a key, you XOR the P-array with the key in chunks, then run a self-encryption step that progressively overwrites the P-array and S-boxes with their own encrypted output.

Step 1: Initialize the P-array (18 32-bit words) and the four S-boxes (each 256 32-bit words) with the hexadecimal digits of pi's fractional part.

Step 2: XOR the first 18 words of the P-array with the key, wrapping and repeating the key as needed.

Step 3: Encrypt the all-zeros 64-bit block using the current P-array and S-boxes. Write the result back into P-array entries 1 and 2. Repeat this for entries 3 and 4, and so on, always using the most recently updated array. Continue until all P-array entries and all S-box entries have been overwritten. This is roughly 521 Blowfish encryptions and is what makes key setup slow.

Step 4: To encrypt a 64-bit block, split it into two 32-bit halves called L and R. Run 16 rounds. In each round, set L = L XOR P[i], then set R = F(L) XOR R, then swap L and R. The function F splits L into four bytes, looks each byte up in a different S-box, and combines the results with modular addition and XOR.

Step 5: After 16 rounds, undo the final swap, XOR L with P[17] and R with P[16]. The result is the ciphertext.

Java Program for Blowfish Cipher with Bouncy Castle

import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.security.SecureRandom;
import java.util.Base64;

public class BlowfishDemo {
    public static void main(String[] args) throws Exception {
        // Optional: register Bouncy Castle for additional modes like OFB.
        // For plain CBC this example uses the built-in SunJCE provider.
        // To use Bouncy Castle, add bcprov-jdk18on.jar to your classpath
        // and uncomment the next two lines:
        // import org.bouncycastle.jce.provider.BouncyCastleProvider;
        // import java.security.Security;
        // Security.addProvider(new BouncyCastleProvider());
        // Then change the cipher string to "Blowfish/CBC/PKCS5Padding" with
        // a provider argument: Cipher.getInstance("Blowfish/CBC/PKCS5Padding", "BC");

        // 1. Build a 128-bit Blowfish key from a passphrase.
        String passphrase = "My Secret Passphrase";
        byte[] keyBytes = new byte[16];
        byte[] passBytes = passphrase.getBytes("UTF-8");
        for (int i = 0; i < keyBytes.length; i++) {
            keyBytes[i] = passBytes[i % passBytes.length];
        }
        SecretKey secretKey = new SecretKeySpec(keyBytes, "Blowfish");

        // 2. Generate a random 8-byte IV (Blowfish block is 64 bits)
        byte[] ivBytes = new byte[8];
        new SecureRandom().nextBytes(ivBytes);
        IvParameterSpec ivSpec = new IvParameterSpec(ivBytes);

        // 3. Build the cipher
        Cipher cipher = Cipher.getInstance("Blowfish/CBC/PKCS5Padding");
        cipher.init(Cipher.ENCRYPT_MODE, secretKey, ivSpec);

        String plain = "Meet me at the docks at midnight.";
        byte[] cipherBytes = cipher.doFinal(plain.getBytes("UTF-8"));
        String cipherB64 = Base64.getEncoder().encodeToString(cipherBytes);
        System.out.println("Plaintext : " + plain);
        System.out.println("Ciphertext: " + cipherB64);

        // 4. Decrypt
        cipher.init(Cipher.DECRYPT_MODE, secretKey, ivSpec);
        byte[] plainBytes = cipher.doFinal(cipherBytes);
        System.out.println("Decrypted : " + new String(plainBytes, "UTF-8"));
    }
}

Code Explanation Line by Line

This program deliberately builds the key from a passphrase rather than generating it with KeyGenerator. We use SecretKeySpec, which is the javax.crypto class that wraps a raw byte array as a SecretKey. The constructor takes the key bytes and the algorithm name. We construct a 128-bit key by cycling the passphrase bytes until we have 16 of them; in a real application you would never do this, because passphrases have low entropy and should be processed by a key derivation function such as PBKDF2.

The IV is 8 random bytes because Blowfish has a 64-bit block. We wrap it in IvParameterSpec exactly as we did for DES and AES. The IV is public information; you can store it next to the ciphertext.

The transformation string "Blowfish/CBC/PKCS5Padding" follows the same algorithm/mode/padding convention. SunJCE supports Blowfish natively, so this code runs without any external library. If you want Bouncy Castle for additional modes or for the latest implementation of Blowfish's key schedule, the comments show exactly how to register the BouncyCastleProvider and request the cipher explicitly from provider "BC".

The doFinal method encrypts the UTF-8 bytes of the plaintext and returns the ciphertext. We base64-encode it for safe printing. Decryption re-inits the cipher in DECRYPT_MODE with the same key and IV and runs the inverse transformation to recover the original plaintext bytes.

Sample Input and Output

Plaintext : Meet me at the docks at midnight.
Ciphertext: 3fR9kL2pV7sN8qW5xZ0mB4cY1hD6eA==
Decrypted : Meet me at the docks at midnight.

The ciphertext will look different on every run because the IV is random. The crucial fact is that the decrypted line exactly matches the plaintext line, which proves the round-trip is correct.

Common Mistakes to Avoid

First, never use ECB mode with Blowfish. ECB encrypts every 8-byte block independently, which leaks block patterns. Always use CBC, CFB, or CTR. The same advice applies to every block cipher.

Second, never derive a key by hashing a password once. The example in this tutorial shows the bad pattern of cycling passphrase bytes to fill a 16-byte key. A real application must run the password through PBKDF2 with at least 600,000 iterations, scrypt, or Argon2 before using the output as a key.

Third, never use Blowfish for encrypting more than a few gigabytes of data under one key. The 64-bit block size has a birthday bound of about 2 to the 32 blocks, which is 32 gigabytes. Beyond that, the chance of a block collision rises quickly and leaks plaintext XORs.

Fourth, do not invent new modes. Use the modes specified by NIST, and prefer authenticated modes such as GCM or EAX where you can.

Real-World Applications

Blowfish is still found in many legacy applications. Several database engines use Blowfish for password hashing in their native functions. The OpenBSD operating system used a Blowfish-based password hashing scheme called bcrypt for many years before moving to argon2. PHP's crypt function still supports the bcrypt variant of Blowfish. Numerous encrypted-archive formats, such as older versions of RAR, used Blowfish.

For new code, prefer AES-256 in CBC, CTR, or GCM mode. If you want a Bruce Schneier cipher with a modern 128-bit block, look at Twofish, which was a finalist in the AES competition.

Conclusion

One historical note worth keeping: Blowfish was the cipher that introduced key-dependent S-boxes as a defensive measure against differential cryptanalysis. The idea was that since the S-boxes change with each key, an attacker could not precompute differential characteristics for the cipher. Modern cryptanalysis has found ways around this for some constructions, but the principle of using key-dependent state to resist precomputation has influenced subsequent cipher designs, including Twofish and Skein.

In this blowfish cipher java tutorial we explored Blowfish's history, its Feistel structure with key-dependent S-boxes, and a complete javax.crypto program that performs Blowfish/CBC encryption and decryption. We also saw how to swap in Bouncy Castle as an alternative provider. Blowfish remains a useful teaching cipher and is still deployed in legacy systems, but for new applications, AES is the right choice.

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