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 12 - Classical Cipher Variants

Java Program to Compare CBC vs ECB Cipher Modes with Diagrams

Reviewed & accurate
AI Summary

Introduction

The cbc vs ecb cipher mode java comparison is one of the most important lessons in modern cryptography. ECB (Electronic Codebook) mode is the simplest block cipher mode, but it is also the most dangerous because identical plaintext blocks produce identical ciphertext blocks. CBC (Cipher Block Chaining) mode fixes this by XORing each plaintext block with the previous ciphertext block before encryption, which diffuses changes across the entire ciphertext. This cbc vs ecb cipher mode java tutorial demonstrates both modes with the same key and plaintext, showing the dramatic difference in output.

The ECB vs CBC comparison is famous in cryptography education because of the ECB penguin. When you encrypt an image of a penguin in ECB mode, the outline of the penguin is still visible in the ciphertext because identical pixel colors produce identical ciphertext blocks. The same image encrypted in CBC mode looks like random noise because the chaining diffuses the structure. We will not use a penguin image here, but we will use a structured plaintext that demonstrates the same effect.

What are CBC and ECB Cipher Modes?

ECB and CBC are block cipher modes of operation. A block cipher like AES encrypts fixed size blocks of 128 bits (16 bytes), but real messages are longer. A mode of operation defines how to apply the block cipher to messages of arbitrary length.

ECB mode is the simplest mode. Each plaintext block is encrypted independently with the same key. Identical plaintext blocks always produce identical ciphertext blocks, which leaks information about the plaintext structure. ECB mode is considered insecure for most uses and should be avoided.

CBC mode is more secure. Each plaintext block is XORed with the previous ciphertext block before encryption. The first block is XORed with an initialization vector (IV). Identical plaintext blocks now produce different ciphertext blocks as long as the previous ciphertext block or IV is different. CBC mode is widely used in TLS, IPsec, and many other protocols.

Compared to ECB, CBC mode requires an IV and a sequential encryption (blocks cannot be encrypted in parallel). Compared to CTR mode, CBC mode is slower for parallel encryption but is more widely supported by older hardware and protocols.

How CBC vs ECB Works Step by Step

Step 1: Choose a key and a plaintext. We use a 16-byte AES key and a 32-byte plaintext consisting of two identical 16-byte blocks. The identical blocks make the ECB weakness obvious.

Step 2: Encrypt the plaintext with ECB mode. The first block is encrypted to a 16-byte ciphertext, and the second block is encrypted to the same 16-byte ciphertext because the plaintext blocks are identical. The output is two identical ciphertext blocks.

Step 3: Encrypt the plaintext with CBC mode. Generate a random 16-byte IV. XOR the first plaintext block with the IV and encrypt to get the first ciphertext block. XOR the second plaintext block with the first ciphertext block and encrypt to get the second ciphertext block. The two ciphertext blocks are different because the chaining input is different.

Step 4: Compare the ciphertexts. The ECB ciphertext has two identical blocks, which leaks the fact that the plaintext has two identical blocks. The CBC ciphertext has two different blocks, which hides the plaintext structure.

Step 5: Decrypt both ciphertexts to verify that the round trips work. The ECB decryption produces the original plaintext directly. The CBC decryption reverses the chaining and produces the original plaintext XORed with the IV at the first block, which is then XORed again to recover the plaintext.

Java Program to Compare CBC vs ECB Cipher Modes


import java.security.SecureRandom;
import java.util.Arrays;
import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.IvParameterSpec;

public class CipherModeComparison {

    public static void main(String[] args) throws Exception {
        // Generate a random AES key
        KeyGenerator kg = KeyGenerator.getInstance("AES");
        kg.init(128);
        SecretKey key = kg.generateKey();

        // Build a plaintext with two identical 16-byte blocks
        byte[] block = "ABCDEFGHIJKLMNOP".getBytes();
        byte[] plain = new byte[32];
        System.arraycopy(block, 0, plain, 0, 16);
        System.arraycopy(block, 0, plain, 16, 16);

        // ECB mode: each block encrypted independently
        Cipher ecb = Cipher.getInstance("AES/ECB/NoPadding");
        ecb.init(Cipher.ENCRYPT_MODE, key);
        byte[] ecbCipher = ecb.doFinal(plain);
        System.out.println("ECB ciphertext block 1: "
            + bytesToHex(Arrays.copyOfRange(ecbCipher, 0, 16)));
        System.out.println("ECB ciphertext block 2: "
            + bytesToHex(Arrays.copyOfRange(ecbCipher, 16, 32)));
        System.out.println("ECB blocks identical: "
            + Arrays.equals(
                Arrays.copyOfRange(ecbCipher, 0, 16),
                Arrays.copyOfRange(ecbCipher, 16, 32)));

        // CBC mode: each block XORed with previous ciphertext block
        byte[] iv = new byte[16];
        new SecureRandom().nextBytes(iv);
        Cipher cbc = Cipher.getInstance("AES/CBC/NoPadding");
        cbc.init(Cipher.ENCRYPT_MODE, key, new IvParameterSpec(iv));
        byte[] cbcCipher = cbc.doFinal(plain);
        System.out.println("CBC ciphertext block 1: "
            + bytesToHex(Arrays.copyOfRange(cbcCipher, 0, 16)));
        System.out.println("CBC ciphertext block 2: "
            + bytesToHex(Arrays.copyOfRange(cbcCipher, 16, 32)));
        System.out.println("CBC blocks identical: "
            + Arrays.equals(
                Arrays.copyOfRange(cbcCipher, 0, 16),
                Arrays.copyOfRange(cbcCipher, 16, 32)));

        // Decrypt CBC to verify round trip
        cbc.init(Cipher.DECRYPT_MODE, key, new IvParameterSpec(iv));
        byte[] recovered = cbc.doFinal(cbcCipher);
        System.out.println("CBC decrypted matches plain: "
            + Arrays.equals(recovered, plain));
    }

    private static String bytesToHex(byte[] bytes) {
        StringBuilder sb = new StringBuilder();
        for (byte b : bytes) sb.append(String.format("%02x", b & 0xff));
        return sb.toString();
    }
}

Code Explanation Line by Line

The main method starts by generating a random 128-bit AES key using KeyGenerator. The key is shared between ECB and CBC modes so the comparison isolates the effect of the mode.

The plaintext is built from two copies of the same 16-byte block. The block contains the string ABCDEFGHIJKLMNOP, which is exactly 16 bytes (the AES block size). The plain array is 32 bytes long, consisting of the block followed by an identical copy of the block. This makes the ECB weakness obvious.

The ECB cipher is created with the transformation string AES/ECB/NoPadding. NoPadding is used because the plaintext is already a multiple of the block size. The cipher is initialized in encrypt mode with just the key (no IV needed for ECB). The doFinal call encrypts the plaintext in one shot, producing a 32-byte ciphertext.

The two 16-byte halves of the ECB ciphertext are compared. Because the plaintext blocks are identical and ECB encrypts each block independently, the two ciphertext blocks are identical. This is the ECB weakness.

The CBC cipher is created with the transformation string AES/CBC/NoPadding. A random 16-byte IV is generated using SecureRandom. The cipher is initialized in encrypt mode with the key and the IV. The doFinal call encrypts the plaintext in one shot, producing a 32-byte ciphertext.

The two 16-byte halves of the CBC ciphertext are compared. Because the chaining XORs each plaintext block with the previous ciphertext block, the two ciphertext blocks are different. This is the CBC strength.

Finally, the CBC cipher is reinitialized in decrypt mode with the same key and IV, and the ciphertext is decrypted. The recovered plaintext matches the original, which confirms the round trip works.

Sample Input and Output

ECB ciphertext block 1: a7f3c5...
ECB ciphertext block 2: a7f3c5... (identical)
ECB blocks identical: true

CBC ciphertext block 1: 9b2c4f...
CBC ciphertext block 2: 71e0a3... (different)
CBC blocks identical: false

CBC decrypted matches plain: true

The ECB ciphertext has two identical blocks, which leaks the fact that the plaintext has two identical blocks. The CBC ciphertext has two different blocks, which hides the plaintext structure. The CBC decryption recovers the original plaintext exactly. The actual hex values vary between runs because the key and IV are random.

Common Mistakes to Avoid

First, using ECB mode for any data with structure. ECB leaks patterns in the plaintext because identical blocks produce identical ciphertext. Never use ECB for encrypting images, database rows, or any data with repeated structures.

Second, reusing the IV in CBC mode. The IV must be unique for each encryption under the same key. Reusing the IV leaks information about the first block and can enable chosen plaintext attacks. Use a random IV for each message.

Third, using a predictable IV in CBC mode. A random IV is best because it is unpredictable to an attacker. A counter IV is also acceptable but must be combined with a nonce to ensure uniqueness across messages.

Fourth, forgetting that CBC mode is malleable. CBC provides confidentiality but not integrity. An attacker can modify the ciphertext and the modification will produce a different plaintext without detection. Use an authenticated encryption mode like GCM if you need both confidentiality and integrity.

Real-World Applications

ECB mode is rarely used in modern production systems because of the weaknesses demonstrated in this tutorial. The most famous illustration of the ECB weakness is the ECB penguin, an image of the Linux mascot Tux encrypted in ECB mode that still shows the outline of the penguin in the ciphertext.

CBC mode is widely used in TLS, IPsec, and many other protocols. TLS 1.2 supports CBC mode for AES, but TLS 1.3 dropped CBC mode in favor of authenticated encryption modes like GCM. CBC mode is still used in legacy systems and in some applications that do not need the integrity guarantees of GCM.

In modern systems, CBC mode is being replaced by authenticated encryption modes like AES-GCM and ChaCha20-Poly1305, which provide both confidentiality and integrity in a single primitive. These modes avoid the malleability weakness of CBC and the padding oracle attacks that have plagued CBC implementations.

In capture the flag events, the ECB vs CBC comparison is a common theme. ECB challenges typically require the solver to recognize the structure in the ciphertext and exploit it. CBC challenges typically involve padding oracle attacks, where the solver uses decryption error messages to recover the plaintext byte by byte.

The CBC vs ECB comparison is also a useful demonstration of the principle of diffusion. CBC mode diffuses changes across the entire ciphertext, so a single bit change in the plaintext affects every subsequent ciphertext block. This is the same principle that motivates the diffusion rounds in modern block ciphers such as AES.

Conclusion

CBC and ECB are block cipher modes of operation. ECB encrypts each block independently, which leaks plaintext structure. CBC chains each block through the previous ciphertext block, which hides plaintext structure. We demonstrated both modes with the same key and a plaintext of two identical blocks, showing that ECB produces identical ciphertext blocks while CBC produces different ciphertext blocks. Next you should study CTR mode (which turns a block cipher into a stream cipher), GCM mode (which adds authentication to CTR mode), and the padding oracle attack (which exploits weaknesses in CBC mode with padding).

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