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 — Extended Module 24 - Additional Block Ciphers

Java Program for Camellia Block Cipher Japanese Standard

Reviewed & accurate
AI Summary

Introduction

The camellia cipher java tutorial covers the Japanese national standard block cipher designed by Mitsubishi Electric and NTT (Nippon Telegraph and Telephone) in 2000. Camellia was selected as a recommended cipher by the CRYPTREC (Cryptography Research and Evaluation Committees) project of the Japanese government in 2002, was selected as a European NESSIE (New European Schemes for Signatures, Integrity, and Encryption) cipher in 2003, and was standardised as ISO/IEC 18033-3 in 2005. Camellia is one of the few ciphers alongside AES that are approved for use in TLS cipher suites by the IETF.

For a Java learner, the camellia cipher java implementation requires Bouncy Castle because the JDK does not ship Camellia. The tutorial shows the Bouncy Castle provider registration pattern and then the Cipher.getInstance("Camellia/CBC/PKCS5Padding", "BC") call, which is the same pattern used by every Twofish, Serpent, IDEA, and SEED Java program.

What is the Camellia Cipher?

Camellia is a symmetric 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 16 bytes (128 bits). Camellia is a Feistel network like DES, Blowfish, and Twofish, not a substitution permutation network like AES and Serpent.

Camellia accepts key sizes of 128, 192, or 256 bits (16, 24, or 32 bytes). The number of rounds is 18 for 128-bit keys and 24 for 192-bit and 256-bit keys. The cipher uses two 8-bit-to-8-bit S-boxes (different from the AES S-box) applied in parallel, a 64-bit half-block diffusion function based on a binary matrix multiplication, and a key schedule that produces 26 or 34 round subkeys.

The Camellia round function operates on the 64-bit halves of the 128-bit block. Each round applies the F function (two S-box layers with a permutation between them) to one half and XORs the result into the other half. After every six rounds, the cipher inserts an additional FL and FL-1 function pair that applies a non-linear bit-sliced transformation to the two halves. This is the design feature that distinguishes Camellia from a plain Feistel cipher.

How Camellia Works - Step by Step

Step 1: Key schedule. The 128, 192, or 256-bit key is mixed with two 128-bit constants and passed through the Camellia round function to produce two intermediate values. These values, combined with the original key, generate the round subkeys. The 18-round variant produces 26 subkeys (one for each round plus four for the initial and final whitening); the 24-round variant produces 34 subkeys.

Step 2: Pre-whitening. The 128-bit plaintext block is XORed with two 64-bit pre-whitening subkeys (kw1 and kw2 in the Camellia specification). This initial key mixing protects against attacks that would otherwise skip the cost of the key schedule.

Step 3: 18 or 24 Feistel rounds. Each round applies the F function to one 64-bit half. The F function consists of a key XOR, a layer of eight S-boxes applied in parallel to the 8 bytes of the half, and a permutation that mixes the bytes. After every six rounds, the FL and FL-1 functions mix the two halves with a different non-linear transformation.

Step 4: Post-whitening. After the last round, the 128-bit block is XORed with two 64-bit post-whitening subkeys (kw3 and kw4). The result is the 128-bit ciphertext.

Step 5: Decryption. The Feistel structure makes decryption the same algorithm as encryption with the round subkeys applied in reverse order. The pre-whitening and post-whitening subkeys swap roles. The FL and FL-1 functions are inverses of each other, so they swap places too. The full cipher is reversible because every component is bijective.

Java Program for Camellia 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 CamelliaDemo.java
//   java  -cp .:bcprov-jdk18on-1.76.jar CamelliaDemo
import org.bouncycastle.jce.provider.BouncyCastleProvider;

public class CamelliaDemo {
    public static void main(String[] args) throws Exception {
        // 1. Register Bouncy Castle so the Cipher factory recognises "Camellia".
        Security.addProvider(new BouncyCastleProvider());

        // 2. Build a 256-bit Camellia key from random bytes.
        byte[] keyBytes = new byte[32];
        new SecureRandom().nextBytes(keyBytes);
        SecretKey key = new SecretKeySpec(keyBytes, "Camellia");
        System.out.println("Key (base64): " + Base64.getEncoder().encodeToString(keyBytes));

        // 3. Generate a random 16-byte IV (Camellia block is 128 bits = 16 bytes).
        byte[] ivBytes = new byte[16];
        new SecureRandom().nextBytes(ivBytes);
        IvParameterSpec iv = new IvParameterSpec(ivBytes);
        System.out.println("IV  (base64): " + Base64.getEncoder().encodeToString(ivBytes));

        // 4. Build the cipher with the Camellia algorithm in CBC mode with PKCS5 padding.
        Cipher cipher = Cipher.getInstance("Camellia/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 call is the same Bouncy Castle registration used in the Twofish and Serpent tutorials. After this call the JCA factory searches Bouncy Castle whenever the SunJCE provider does not implement the requested algorithm. The BouncyCastleProvider class is in the org.bouncycastle.jce.provider package of the bcprov-jdk18on JAR.

The key is 32 bytes (256 bits), which is the maximum Camellia key length. The SecretKeySpec wraps the bytes with the algorithm name Camellia, which Bouncy Castle recognises. Camellia supports 128, 192, and 256-bit keys; the 256-bit variant uses 24 rounds instead of the 18 rounds of the 128-bit variant.

The IV is 16 bytes (128 bits), which is the Camellia block size. The IV is wrapped into an IvParameterSpec and passed to the cipher.init call. The IV does not need to be secret; it can be prepended to the ciphertext or stored alongside it. The IV needs to be unpredictable, which SecureRandom guarantees.

The Cipher.getInstance("Camellia/CBC/PKCS5Padding", "BC") call requests the Camellia algorithm from Bouncy Castle explicitly. The transformation string has the same algorithm/mode/padding structure as the Triple DES, AES, Twofish, and Serpent examples. The two-argument form of getInstance forces Bouncy Castle even if another provider has registered the algorithm.

The encrypt and decrypt calls follow the standard javax.crypto pattern. The doFinal call on the encrypt path runs the 18 or 24 Camellia rounds with the FL/FL-1 insertions every six rounds. The doFinal call on the decrypt path runs the inverse rounds and removes the PKCS5 padding. The decrypted bytes match the original plaintext bytes, which is the proof that the cipher chains correctly.

Sample Input and Output

Key (base64): 8r+/+z89/vf7//v/+/8+Pz8/Pz9AQEBAQEBAQEBAQEA=
IV  (base64): 0nTv+vr6/v8/Pz8/Pz8/Pw==
Plaintext : Meet me at the docks at midnight.
Ciphertext: rT2uL9nQ4cZ1fVhJ8sN5xE+oWkP3mZcB/aB7yD2nOoE=
Decrypted : Meet me at the docks at midnight.

The key and IV in this sample are cryptographically random bytes encoded in base64. The ciphertext will look different on every run because the key and IV are randomly generated each time. The crucial check is that the decrypted line exactly matches the plaintext line, which proves the 18 or 24 Camellia rounds chain correctly in both directions.

Common Mistakes to Avoid

First, forgetting to register Bouncy Castle. Without Security.addProvider(new BouncyCastleProvider()) the Cipher.getInstance("Camellia/CBC/PKCS5Padding", "BC") call will throw NoSuchProviderException because the "BC" provider is not registered. The registration must happen before any getInstance call that targets Bouncy Castle.

Second, using ECB mode. The transformation "Camellia/ECB/PKCS5Padding" encrypts every 16-byte block independently with no chaining, which leaks block patterns. The ECB penguin diagram shows the danger. Always use CBC, CFB, CTR, or GCM with a random IV.

Third, reusing the IV with the same key. CBC mode requires a fresh unpredictable IV for every message. If the IV repeats under the same key, the first ciphertext block leaks the XOR of the two first plaintext blocks, which is the catastrophic failure that broke WEP.

Fourth, assuming Camellia is a drop-in replacement for AES. Camellia has stood up to 20 years of public cryptanalysis, but AES has had more scrutiny and has hardware acceleration on every modern CPU. Use Camellia when you have a specific reason (Japanese regulatory compliance, interoperability with a Camellia-only system); otherwise use AES.

Real-World Applications

Camellia is deployed in production in the financial sector and in the TLS ecosystem. The TLS cipher suite TLS_RSA_WITH_CAMELLIA_256_CBC_SHA was standardised in RFC 4132 by Aoki, Kanda, Kato, and Tsujii in 2005, and a Camellia GCM cipher suite was standardised in RFC 5529 in 2009. The Mozilla Firefox and Google Chrome browsers historically supported Camellia in TLS, though both have removed Camellia from their default cipher list as AES-GCM has become dominant.

In Japan, Camellia is mandatory in the financial sector per the Japanese Industrial Standard JIS X 9702 and the CRYPTREC guideline. The Japanese government requires Camellia for cryptographic protection of personal information in the resident registry and the basic resident register network. The Japanese electric vehicle charging standard CHAdeMO uses Camellia for the charging cable communication.

The OpenSSL library ships Camellia as a supported cipher (the openssl enc -camellia-256-cbc command). The Libgcrypt library used by GnuPG ships Camellia. The Linux kernel dm-crypt disk encryption subsystem supports Camellia alongside AES, Twofish, and Serpent. For new production applications, AES-GCM is the default choice, but Camellia remains the cipher of choice for Japanese regulatory compliance and for systems that need a cipher other than AES for diversification.

Conclusion

In this camellia cipher java tutorial we walked through the 128-bit block, the 256-bit key, the 18 or 24-round Feistel structure with FL/FL-1 insertions, and a complete Bouncy Castle program that performs Camellia/CBC encryption and decryption. Camellia is the Japanese national standard cipher that stands alongside AES in the TLS cipher suite list. Next, study the IDEA tutorial for the older Swiss cipher used in PGP, the SEED tutorial for the Korean national standard, and the AES tutorial for the cipher that the rest of the world has standardised on.

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