Introduction
The cast5 cipher java tutorial covers a 64-bit block cipher designed by Carlisle Adams and Stafford Tavares at Queen's University in Kingston, Ontario and published in 1996. CAST-128, as the official name spells it, was standardised as RFC 2144 by the IETF in May 1997. The cipher name comes from the initials of the inventors' last names (Carlisle Adams, Stafford Tavares), a naming convention that has survived into the later CAST-256 cipher published in 2000.
For a Java learner, the cast5 cipher java implementation is interesting because CAST-128 was the default symmetric cipher in PGP 5.0 and later versions before AES displaced it, and it remains one of the optional ciphers in OpenPGP (RFC 4880). The JDK does not ship CAST-128 in its SunJCE provider, so this tutorial shows the Bouncy Castle provider pattern that you also use for Twofish, Serpent, and SEED. The cipher is a textbook Feistel network with key-dependent rotation amounts and three different S-box types per round, which makes it a good study example for cipher design.
What is the CAST5 Cipher?
CAST5 is a symmetric Feistel block cipher. It is symmetric because the same key is used for encryption and decryption, and it is a block cipher because it processes the plaintext in fixed-size blocks of 8 bytes (64 bits). CAST5 belongs to the same Feistel family as DES, Blowfish, and Twofish.
CAST5 accepts key sizes from 40 to 128 bits (5 to 16 bytes) in 8-bit increments. The number of rounds depends on the key size: 12 rounds for keys up to 80 bits and the full 16 rounds for keys of 80 to 128 bits. The full 16-round CAST5 with a 128-bit key is the variant that PGP and OpenPGP use.
The round function is the heart of CAST5. Each round splits the 64-bit block into two 32-bit halves, runs the right half through a round function f, and XORs the result into the left half. The f function uses four S-boxes per round, with the S-boxes selected from eight fixed S-box tables (S1 through S4 for rounds 1, 4, 7, 10, 13, 16; S5 through S8 are used for the other rounds). The round function also adds a 32-bit round subkey and applies a key-dependent rotation amount that comes from the lower five bits of the subkey, which is the defensive trick that makes CAST5 resistant to differential cryptanalysis.
How CAST5 Works - Step by Step
Step 1: Key schedule. The 128-bit key (or smaller 40- to 80-bit key) is fed through a complex schedule that uses eight S-boxes (the same S-boxes used in the round function) and a series of XOR, addition, and rotation operations. The schedule produces 16 pairs of 32-bit round subkeys: one subkey per round for the round function input, and one subkey per round for the rotation amount (the lower five bits of one subkey select the rotation amount).
Step 2: Block splitting. The 8-byte plaintext block is split into two 32-bit halves L0 and R0 in big-endian byte order. The Feistel structure alternates between the halves: in odd rounds L is modified, in even rounds R is modified (or the other way around depending on the convention).
Step 3: 16 rounds. Each round i (1 to 16) takes the right half Ri-1, adds (or XORs, or subtracts) the round subkey Kmi depending on the round type, applies the four S-box lookups, performs a key-dependent rotation, and XORs the result into the left half. The three round types alternate: type 1 (rounds 1, 4, 7, 10, 13, 16) uses addition and subtraction; type 2 (rounds 2, 5, 8, 11, 14) uses XOR; type 3 (rounds 3, 6, 9, 12, 15) uses subtraction and addition.
Step 4: Final swap. After 16 rounds, the two halves are swapped one final time (which is the inverse of the per-round swap). The result is the 8-byte ciphertext block.
Step 5: Decryption. The Feistel structure makes decryption identical to encryption with the round subkeys applied in reverse order. Subkey 16 becomes subkey 1, subkey 15 becomes subkey 2, and so on. This is the standard Feistel property that DES, Blowfish, and Camellia all share.
Java Program for CAST5 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.Security;
import java.security.SecureRandom;
import java.util.Base64;
// Requires Bouncy Castle on the classpath:
// org.bouncycastle:bcprov-jdk18on:1.76
// Compile and run:
// javac -cp bcprov-jdk18on-1.76.jar Cast5Demo.java
// java -cp .:bcprov-jdk18on-1.76.jar Cast5Demo
import org.bouncycastle.jce.provider.BouncyCastleProvider;
public class Cast5Demo {
public static void main(String[] args) throws Exception {
// 1. Register Bouncy Castle so the Cipher factory recognises "CAST5".
Security.addProvider(new BouncyCastleProvider());
// 2. Build a 128-bit CAST5 key from random bytes.
byte[] keyBytes = new byte[16];
new SecureRandom().nextBytes(keyBytes);
SecretKey key = new SecretKeySpec(keyBytes, "CAST5");
System.out.println("Key (base64): " + Base64.getEncoder().encodeToString(keyBytes));
// 3. Generate a random 8-byte IV (CAST5 block is 64 bits = 8 bytes).
byte[] ivBytes = new byte[8];
new SecureRandom().nextBytes(ivBytes);
IvParameterSpec iv = new IvParameterSpec(ivBytes);
System.out.println("IV (base64): " + Base64.getEncoder().encodeToString(ivBytes));
// 4. Build the cipher with CAST5 in CBC mode with PKCS5 padding.
Cipher cipher = Cipher.getInstance("CAST5/CBC/PKCS5Padding", "BC");
cipher.init(Cipher.ENCRYPT_MODE, key, iv);
String plain = "Meet me at the docks at midnight.";
byte[] cipherBytes = cipher.doFinal(plain.getBytes("UTF-8"));
System.out.println("Plaintext : " + plain);
System.out.println("Ciphertext: " + Base64.getEncoder().encodeToString(cipherBytes));
// 5. Decrypt with the same key and IV.
cipher.init(Cipher.DECRYPT_MODE, key, iv);
byte[] plainBytes = cipher.doFinal(cipherBytes);
System.out.println("Decrypted : " + new String(plainBytes, "UTF-8"));
}
}
Code Explanation - Line by Line
The Security.addProvider(new BouncyCastleProvider()) call registers Bouncy Castle as a JCA (Java Cryptography Architecture) provider. After this call, every Cipher.getInstance, MessageDigest.getInstance, and KeyAgreement.getInstance call will also search Bouncy Castle for the requested algorithm. The BouncyCastleProvider class lives in the org.bouncycastle.jce.provider package in the bcprov-jdk18on JAR.
The key is 16 bytes (128 bits), the maximum CAST5 key length. The SecretKeySpec wraps the raw bytes with the algorithm name CAST5, which Bouncy Castle recognises. The 8-byte IV is the CAST5 block size (64 bits = 8 bytes), which is the same as DES and Triple DES.
The cipher is built with Cipher.getInstance("CAST5/CBC/PKCS5Padding", "BC"). The two-argument form of getInstance requests the algorithm from the named provider, which forces Bouncy Castle even if another provider has registered the algorithm first. The transformation string has the same algorithm/mode/padding structure as the Triple DES and AES examples.
The ENCRYPT_MODE initialisation takes the key and the IvParameterSpec. The doFinal call runs the 16 CAST5 rounds with the four S-box lookups, the key-dependent rotation, and the round subkey addition derived from the 16-byte key. The 8-byte IV chains the blocks together through CBC mode.
Decryption re-initialises the cipher in DECRYPT_MODE with the same key and IV. The Feistel structure makes decryption the same algorithm as encryption with reversed round subkeys, so the doFinal call runs the same 16 rounds in reverse and removes the PKCS5 padding.
Sample Input and Output
Key (base64): 9J3jU/uPfI/z2H9J5Vkqo1rE4I5xYbA+dTpTzP8LpR0= IV (base64): 7+8BAwQFBgcICQoLDA0ODw== Plaintext : Meet me at the docks at midnight. Ciphertext: 2vP+BRuoG5mzp1qYr8sN3tW2yY8TqZ7J0hFkM9s= Decrypted : Meet me at the docks at midnight.
The key and IV in this sample are 16 bytes and 8 bytes of cryptographically random output. The ciphertext will look different on every run because the key and IV are randomly generated. The check that matters is that the decrypted line matches the plaintext line, which proves the 16 CAST5 rounds chain correctly in both directions.
Common Mistakes to Avoid
First, forgetting to call Security.addProvider before the Cipher.getInstance call. Without the registration, the JCA factory will throw a NoSuchAlgorithmException for "CAST5" because the SunJCE provider does not implement it. Either call addProvider in a static initializer at the top of the class, or list the provider in the java.security file shipped with the JDK.
Second, using ECB mode. The transformation "CAST5/ECB/PKCS5Padding" encrypts every 8-byte block independently with no chaining. Identical plaintext blocks produce identical ciphertext blocks, which leaks the structure of the plaintext. Always use CBC, CFB, CTR, or GCM with a random IV.
Third, using a short key. CAST5 accepts keys as short as 40 bits (5 bytes), but 40-bit keys are well within brute-force range for modern hardware. RFC 2144 explicitly recommends 128-bit keys for new applications. Use the full 16-byte key length.
Fourth, using CAST5 for new applications. The 64-bit block size has a birthday bound of about 2 to the 32 blocks (32 GB of data) under one key, beyond which block collisions leak plaintext XORs. Use AES-128 or AES-256 with 128-bit blocks for new applications, and reserve CAST5 for compatibility with legacy PGP and OpenPGP messages.
Real-World Applications
CAST5 is deployed in the OpenPGP ecosystem. RFC 4880 (OpenPGP, November 2007) lists CAST5 with a 128-bit key as one of the mandatory-to-implement symmetric ciphers, alongside AES-128, AES-192, AES-256, Triple DES, and IDEA. The GnuPG open source implementation supports CAST5 with the cipher-algo cast5 command line option, and CAST5 was the default symmetric cipher in GnuPG 1.x before AES displaced it in GnuPG 2.x.
The Pretty Good Privacy (PGP) standard from Phil Zimmermann used CAST5 as the default symmetric cipher in PGP 5.0 (1997), PGP 6.x, and PGP 7.x. The cipher was chosen because it was unencumbered by patents (unlike IDEA, which was patented in Europe and the United States) and because it had survived public review through RFC 2144. Symantec's commercial PGP implementation still ships CAST5 for backward compatibility with old encrypted archives.
For new applications, CAST5 has been displaced by AES. The 64-bit block is the main weakness: the Sweet32 attack (Bhargavan and Leurent, 2016) showed that any 64-bit block cipher in CBC mode leaks plaintext after about 32 GB of data encrypted under the same key. PGP and OpenPGP implementations now default to AES-256 and treat CAST5 as a legacy option.
Conclusion
In this cast5 cipher java tutorial we walked through the 64-bit block, the 128-bit key, the 16-round Feistel structure with key-dependent rotation, and a complete Bouncy Castle program that performs CAST5/CBC encryption and decryption. CAST5 is the cipher you meet when you work with legacy PGP archives or with OpenPGP software that still lists it as mandatory. Next, study the AES tutorial for the modern global standard, the Blowfish tutorial for another 64-bit Feistel cipher, and the Bouncy Castle provider documentation for the full list of algorithms the library supports.
Comments
Comments
Post a Comment