1. Overview

Originally designed as an alternative to the DES encryption algorithm, the Blowfish encryption algorithm is one of the most popular encryption algorithms available today. Blowfish is a symmetric-key block cipher designed by Bruce Schneier in 1993. This algorithm has a block size of 64 bits and a key length of 446 bits, which is better than the DES and 3DES algorithms.

In this tutorial, we’ll learn how to implement encryption and decryption using Blowfish ciphers with the Java Cryptography Architecture (JCA) available in JDK.

2. Generating Secret Key

Since Blowfish is a symmetric-key block cipher, it uses the same key for both encryption and decryption. Accordingly, we’ll create a secret key to encrypt texts in the next steps. This secret key should be preserved securely and shouldn’t be shared in public. Let’s define the secret key:

// Generate a secret key
String secretKey = "MyKey123";
byte[] keyData = secretKey.getBytes();

// Build the SecretKeySpec using Blowfish algorithm
SecretKeySpec secretKeySpec = new SecretKeySpec(keyData, "Blowfish");

Next, we can proceed to build the cipher with encryption mode:

// Build the cipher using Blowfish algorithm
Cipher cipher = Cipher.getInstance("Blowfish");

Then, we’ll initialize the cipher with encryption mode (Cipher.ENCRYPT_MODE) and use our secret key:

// Initialize cipher in encryption mode with secret key
cipher.init(Cipher.ENCRYPT_MODE, secretKeySpec);

3. Encrypting Strings

Let’s see how to use the instantiated Blowfish cipher with the secret key to encrypt Strings:

// the text to encrypt
String secretMessage = "Secret message to encrypt";

// encrypt message
byte[] encryptedBytes = cipher.doFinal(secretMessage.getBytes(StandardCharsets.UTF_8));

As we can see, the cipher gives us an encrypted message in the form of a byte array. However, if we’d like to store it in a database or send the encrypted message via REST API, it would be more suitable and safer to encode it with the Base64 alphabet:

// encode with Base64 encoder
String encryptedtext = Base64.getEncoder().encodeToString(encryptedBytes);

Now, we get the final encrypted text, which is readable and easy to handle.

4. Decrypting Strings

Decrypting Strings with the Blowfish encryption algorithm is equally simple. Let’s see it in action.

First, we need to initialize the cipher with decryption mode (Cipher.DECRYPT_MODE) along with the SecretKeySpec:

// Create the Blowfish Cipher
Cipher cipher = Cipher.getInstance("Blowfish");
// Initialize with decrypt mode & SecretKeySpec
cipher.init(Cipher.DECRYPT_MODE, secretKeySpec);

Next, we can use this cipher to decrypt the message:

// decode using Base64 and decrypt the message
byte[] decrypted = cipher.doFinal(Base64.getDecoder().decode(encryptedtext));
// convert the decrypted bytes to String
String decryptedString = new String(decrypted, StandardCharsets.UTF_8);

Finally, we can verify the results to ensure the decryption process performs correctly by comparing it to the original value:

Assertions.assertEquals(secretMessage, decrypedText);

In addition, we can notice that we use StandardCharsets.UTF_8 charset during both encryption and decryption. This way, we can be sure that encryption or decryption always replaces the input text containing malformed and unmappable char sequences with the replacement byte array of UTF-8 charset.

5. Working With Files

Sometimes, we may need to encrypt or decrypt the whole file instead of individual Strings. The Blowfish encryption algorithm allows to encrypt and decrypt the whole files. Let’s see an example to create a temp file with some sample content:

String originalContent = "some secret text file";
Path tempFile = Files.createTempFile("temp", "txt");
writeFile(tempFile, originalContent);

Next, we need to transform the content into a byte array:

byte[] fileBytes = Files.readAllBytes(tempFile);

Now, we can proceed with the encryption of the whole file using encryption cipher:

Cipher encryptCipher = Cipher.getInstance("Blowfish");
encryptCipher.init(Cipher.ENCRYPT_MODE, secretKeySpec);
byte[] encryptedFileBytes = encryptCipher.doFinal(fileBytes);

Finally, we can overwrite the encrypted content in the temp file:

try (FileOutputStream stream = new FileOutputStream(tempFile.toFile())) {
    stream.write(encryptedFileBytes);
}

Decrypting the whole file is a similar process. The only difference is to change the cipher mode to do decryption:

encryptedFileBytes = Files.readAllBytes(tempFile);
Cipher decryptCipher = Cipher.getInstance("Blowfish");
decryptCipher.init(Cipher.DECRYPT_MODE, secretKeySpec);
byte[] decryptedFileBytes = decryptCipher.doFinal(encryptedFileBytes);
try (FileOutputStream stream = new FileOutputStream(tempFile.toFile())) {
    stream.write(decryptedFileBytes);
}

Finally, we can verify whether the file content matches the original value:

String fileContent = readFile(tempFile);
Assertions.assertEquals(originalContent, fileContent);

6. Weakness and Successors

Blowfish was one of the first secure encryption algorithms not subject to patents and freely available for public use. Although the Blowfish algorithm performs better than DES and 3DES algorithms in terms of encryption speed, it has some limitations due to its inherent design.

The Blowfish algorithm uses a 64-bit block size as opposed to AES’s 128-bit block size. Hence, this makes it vulnerable to birthday attacks, specifically in the HTTPS context. Attackers have already demonstrated that they can leverage the 64-bit block size ciphers to perform plaintext recovery (by decrypting ciphertext). Moreover, because of its small block size open-source projects such as GnuPG recommend that the Blowfish algorithm won’t be used to encrypt files larger than 4 GB.

Changing new secret keys slows down the process. For instance, each new key needs pre-processing and takes about 4 KB of text, which is slower when compared to other block ciphers.

Bruce Schneier has recommended migrating to his Blowfish successor, the Twofish encryption algorithm, which has a block size of 128 bits. It also has a free license and is available for public use.

In 2005, Blowfish II was released, which was developed by people other than Bruce Schneier. Blowfish II has the same design but has twice as many S tables and uses 64-bit integers instead of 32-bit integers. Also, it works on 128-bit blocks like the AES algorithm.

Advanced Encryption Standard (AES) is a popular and widely used symmetric-key encryption algorithm. AES supports varying key lengths such as 128, 192, and 256 bits to encrypt and decrypt data. However, its block size is fixed at 128 bits.

7. Conclusion

In this article, we learned about the generation of secret keys and how to encrypt and decrypt Strings using the Blowfish encryption algorithm. Also, we saw encrypting and decrypting files are equally simple. Finally, we also discussed the weaknesses and various successors of Blowfish.

As always, the full source code of the article is available over on GitHub.

Course – LSS (cat=Security/Spring Security)

I just announced the new Learn Spring Security course, including the full material focused on the new OAuth2 stack in Spring Security:

>> CHECK OUT THE COURSE
res – Security (video) (cat=Security/Spring Security)
2 Comments
Oldest
Newest
Inline Feedbacks
View all comments
Comments are open for 30 days after publishing a post. For any issues past this date, use the Contact form on the site.