Lesson 5 of 15

Block Cipher Modes

Block Cipher Modes of Operation

A block cipher encrypts fixed-size blocks of plaintext. The same key encrypts each block, but modes of operation define how blocks are chained together. The choice of mode dramatically affects security.

ECB — Electronic Codebook

The simplest mode: each block is encrypted independently.

Ci=Ek(Pi)C_i = E_k(P_i)

Fatal flaw: identical plaintext blocks produce identical ciphertext blocks. The famous "ECB penguin" — encrypting a bitmap in ECB mode reveals the image structure.

CBC — Cipher Block Chaining

Each block is XORed with the previous ciphertext block before encryption:

Ci=Ek(PiCi1)C_i = E_k(P_i \oplus C_{i-1})

The first block uses an Initialization Vector (IV):

C0=Ek(P0IV)C_0 = E_k(P_0 \oplus IV)

Decryption:

Pi=Dk(Ci)Ci1P_i = D_k(C_i) \oplus C_{i-1}

CBC eliminates the ECB pattern flaw. Each ciphertext block depends on all previous plaintext blocks.

Our Simulation

We simulate the block cipher EkE_k with simple XOR: Ek(x)=xkE_k(x) = x \oplus k.

  • ECB: Ci=PikC_i = P_i \oplus k
  • CBC encrypt: Ci=(PiCi1)kC_i = (P_i \oplus C_{i-1}) \oplus k, starting with C1=IVC_{-1} = IV
  • CBC decrypt: Pi=(Cik)Ci1P_i = (C_i \oplus k) \oplus C_{i-1}

Your Task

Implement:

  • ecb_encrypt(blocks, key) — XOR each block with key
  • cbc_encrypt(blocks, key, iv) — CBC encryption
  • cbc_decrypt(blocks, key, iv) — CBC decryption
Python runtime loading...
Loading...
Click "Run" to execute your code.