Chapter 3 - Cipher Type and Mode of Operations

Updated 4 Oct 2026

Types of Cipher Operations

Stream Ciphers

  • Encrypt and decrypt one digit or one character at a time

Block Ciphers

  • Encrypt and decrypt data in groups of bits or a block

Stream Ciphers

Definition

  • A symmetric key cipher where plaintext digits are combined with a pseudorandom cipher digit stream (a key stream) one at a time
  • Each plaintext digit is combined with the corresponding digit of the keystream to produce a ciphertext digit

Characteristics

  • The input plaintext is processed continuously
  • Each key is generated via pseudorandom number generator
    • In programming, we can call the standard library/function.
  • The output ciphertext is produced as a stream of random-like numbers (unpredictable)

Advantages

  • Fast and use simple code

Analogy: Think of stream ciphers like painting a wall with a spray gun - you're applying color continuously, one spot at a time, rather than painting in large sections.


Pseudorandom Number Generator (PRNG)

Definition

  • Also known as a deterministic random bit generator (DRBG)
  • An algorithm for generating a sequence of numbers whose properties approximate the properties of sequences of random numbers

Key Property

  • The PRNG-generated sequence is not truly random
  • It is completely determined by an initial value, called the PRNG's seed (which may include truly random values)

Stream Cipher Architecture


Encryption:
Ci=Pi⊕ki\boxed{C_i = P_i \oplus k_i}

Decryption:
Pi=Ci⊕ki\boxed{P_i = C_i \oplus k_i}

Where:

  • PiP_i = plaintext byte
  • CiC_i = ciphertext byte
  • kik_i = keystream byte
  • ⊕\oplus = XOR operation

Analogy: A PRNG is like a magic box that, given the same starting number (seed), will always produce the same sequence of "random" numbers - like a shuffled deck of cards that's shuffled the exact same way each time.


Stream Cipher Example

Encryption:

1100 1100  ← input plaintext
⊕
0110 1100  ← key stream
─────────
1010 0000  ← output ciphertext

Decryption:

1010 0000  ← input ciphertext
⊕
0110 1100  ← key stream
─────────
1100 1100  ← output plaintext

Stream Cipher Design Considerations

  1. Key stream should have a large enough period of producing no repeated encryption sequence
  2. Key stream approximates true random number properties
  3. Uses a sufficient long initial key to resist brute-force attack
    • With current technology, should be at least 128 bits

Stream Ciphers Security

Common Misconception

  • Stream ciphers are often viewed as weak ❌
    • This is not generally true - they are useful and secure ✓

Benefits

  • Fast performance
  • No fixed block size
  • Errors do not propagate

Drawbacks

  • No message integrity check
  • The devil is in the details

Important Usage Note

  • ==They do need to be used with care==
  • If you don't follow the algorithm to the letter, things can go very bad

Analogy: Stream ciphers are like a high-performance sports car - incredibly fast and efficient, but you need to follow the operating manual exactly or you risk serious problems.


Keystream Generators

Requirements

  • Cannot use a true random sequence of sufficient length (similar to OTP), since this would require another secure channel
  • Alternative: Use a pseudorandom sequence, created through a known (deterministic) procedure that is "seeded" with a shorter key

Properties

  • Since the generator is deterministic and finite, the sequence is periodic
  • It is not enough that the output "seems" random
  • If the seed (key) is unknown, every output bit (byte, ...) should be unpredictable given the already generated sequence

Key generation is critical for security. Generating keys using simple or custom algorithms cannot guarantee safety. Always use well-established cryptographic libraries, such as Node.js’s built-in crypto module, which provides secure random key generation.


Randomness

Two Key Properties

1. Uniform Distribution

  • The frequency of occurrence of each of the numbers should be approximately the same
  • To avoid obvious pattern.

เหมือนเดาข้อสอบไง เวลากำหนดคำตอบก็ต้อง Distribute ให้มันเท่ากัน จะได้เดาไม่ได้

2. Independence

  • No one value in the sequence can be inferred from the others

Pseudorandom vs True Random

Computer Limitation

  • Computers are deterministic devices - a computer's behavior is entirely predictable, by design
  • To create something unpredictable, computers use mathematical algorithms to produce numbers that are "random enough"

Pseudorandom Characteristics

  • Deterministic algorithm → produces sequences of numbers that are not statistically random
  • BUT reasonable and pass many reasonable tests of randomness

Analogy: True randomness is like rolling physical dice - truly unpredictable. Pseudorandomness is like a computer simulation of dice rolling - it looks random, but if you know the starting conditions, you can predict all future rolls.


PRNG vs PRF

Pseudorandom Number Generator (PRNG)

  • An algorithm that is used to produce an open-ended sequence of bits
  • Referred to as a PRNG
  • A common application: input to a symmetric stream cipher

Pseudorandom Function (PRF)

  • A PRF is used to produce a pseudorandom string of bits of some fixed length
  • Examples: symmetric encryption keys and nonces
  • The PRF takes as input a seed plus some context specific values (such as a user ID or an application ID)

Key Points

  • Other than the number of bits produced, there is no difference between a PRNG and a PRF
  • The same algorithms can be used in both applications
  • Both require a seed and both must exhibit randomness and unpredictability
  • A PRNG application may also employ context-specific input

  • Context-specific values ก็สามารถใส่ได้อย่างเช่น IP-Address เข้าไป …

Keystream Period Requirements

อย่าลืมเอา Python มาใส่ด้วย

Problem: Keystream Repetition

A stream cipher encrypts as:
Ci=Pi⊕Ki\boxed{C_i = P_i \oplus K_i}

If the keystream repeats:
Ki=Kj⇒Ci⊕Cj=Pi⊕PjK_i = K_j \Rightarrow C_i \oplus C_j = P_i \oplus P_j

This leaks direct relations between plaintexts, enabling:

  • Known-plaintext attacks
  • Two-time pad attacks (classic RC4 failures)

If we use that same key, so it may result in the same output (hacker can see pattern)

Requirement

  • Keystream period must be much larger than any message length
  • Modern designs aim for periods ≥ 21282^{128}

Analogy: If a keystream repeats, it's like using the same one-time pad twice - the "one-time" security guarantee breaks down completely.


Cryptographic Security of Keystream Generators

Vulnerability: Known Plaintext Attack

  • A known plaintext attack will make part of the sequence known to the cryptanalyst (attacker)
  • The attacker knows at least one sample of both the plaintext and the ciphertext
  • If the XOR cipher is used, this will reveal the key as: key=plaintext⊕ciphertext\text{key} = \text{plaintext} \oplus \text{ciphertext}

Defense: Long Period

  • The sequence is periodic
  • A known plaintext attack needs the period to be as long as possible, since the known part repeats after the period length

Keystream Generator Example: A5/1

A5/1 (GSM Cellular Telephone)

  • An Linear Feedback Shift Register-based (LFSR) stream cipher
  • Used to encrypt mobile phone conversations

LFSR Definition

  • A shift register whose input bit is a linear function of its previous state
  • Most often a shift register whose input bit is driven by the XOR of some bits of the overall shift register value

A5/1 Architecture

  • Uses three LFSRs with different lengths:
    • Register 1: 19 bits (taps at positions 18, 17, 16, 13)
    • Register 2: 22 bits (taps at positions 21, 20)
    • Register 3: 23 bits (taps at positions 22, 21, 20, 7)

Analogy: An LFSR is like a mechanical adding machine where certain gears feed back into the input, creating a complex but deterministic pattern.


RC4 (Rivest Cipher)

Algorithm that uses stream cipher. Considered as not secure anymore!

History

  • Designed by Ron Rivest in 1987
  • Originally kept as a trade secret
  • Anonymously posted on the Internet in September 1994

Characteristics

  • Variable key-size (40-2048 bits)
  • Byte-oriented operations
  • Based on the use of a random permutation

Applications (Historical)

  • Used in SSL/TLS, WEP, WPA protocols
  • Part of WEP in 1997 and WPA in 2003/2004 for wireless cards
  • Part of SSL in 1995 and its successor TLS in 1999

Current Status

  • Prohibited for all versions of TLS by RFC 7465 in 2015
  • Due to RC4 attacks weakening or breaking RC4 used in SSL/TLS

RC4 Architecture

Encryption Key
     ↓
KSA (Key Scheduling Algorithm)
     ↓
Pseudo-random generator Algorithm
     ↓
Plain Text ⊕ Keystream → Cipher Text

RC4 is No Longer Secure

Major Vulnerability

  • There is a serious bias of probability distribution of keystream
  • Therefore attacker can attack the encrypted message by using known-plaintext attacks

Example Attack Scenario

User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64;
Trident/7.0; rv:11.0) like Gecko
Host: a.site.com              ← Headers are
Connection: Keep-Alive           predictable
Cache-Control: no-cache
Cookie: auth=????????????????> P=aaaaaaaaaaaaaaa
         ↑                              ↑
   Surrounded by known            Headers are
   plaintext at both sides        predictable

Analogy: RC4's bias is like a loaded die - it looks random at first, but if you track enough rolls, you'll notice certain numbers come up more often than they should.

RC4-Based Protocols (Historical)

  • WEP (Wired Equivalent Privacy)
  • WPA - WiFi-Protected Access (default algorithm, but can be configured to use AES-CCMP instead of RC4)
  • BitTorrent protocol encryption
  • Microsoft Office XP (insecure implementation since nonce remains unchanged when documents get modified)
  • Microsoft Point-to-Point Encryption
  • Transport Layer Security / Secure Sockets Layer (was optional, then prohibited in RFC 7465)
  • Secure Shell (optionally)
  • Remote Desktop Protocol (optionally)
  • Kerberos (optionally)
    • Authentication service, หมาสามหัวเฝ้าประตูนรก
    • Talk again after midterm
  • PDF
  • Skype (in modified form)

ChaCha20

Modern stream cipher

Overview

  • ChaCha20 is a modern stream cipher
  • Designed by Daniel J. Bernstein
  • Standardized in RFC 8439
    • RFC: Request for comments
  • Widely used in TLS 1.3, QUIC, WireGuard
    • TLS: Transport Layer Security
      • Different version, stronger version of SSL

Key Characteristics

  • Cipher type: Stream cipher
  • Design style: ARX (Addition–Rotation–XOR)
  • Key size: 256 bits
  • Nonce: 96 bits (Nonce: another set of random number)
  • Counter: 32 bits

Name Origin

  • ChaCha20 = ChaCha stream cipher with 20 rounds

ChaCha20 Encryption Principle

Inputs

Key (256-bit)
Nonce (96-bit)
Counter
    ↓
ChaCha20
    ↓
Keystream ──┐
            │ XOR (Bit-by-bit)
Plaintext ──┘
    ↓
Ciphertext

Encryption Formula

C=P⊕Keystream\boxed{C = P \oplus \text{Keystream}}

Key Generation

  • Keystream is generated from (key, nonce, counter)

Properties

  • No padding required
  • Byte-oriented
  • Low latency

ChaCha20-Poly1305 (AEAD)

Components

ChaCha20
  • Generates a one-time key for Poly1305
  • Encrypts data
Poly1305
  • Computes an authentication tag
  • Authenticates data + metadata

Security Properties

  • Confidentiality (from ChaCha20)
  • Integrity (from Poly1305)
  • Authenticity (from Poly1305)

Poly1305 Name Origin

  • 1305 → refers to the prime number 2130−52^{130} - 5 used internally

Receiver Process

  • Receiver verifies the tag before accepting plaintext

Architecture Overview

Secret Key (256-bit)
         ↓
    ┌────────────────┐
    │    ChaCha20    │
    │(Block Function)│
    └────────────────┘
         ↓
    ┌────┴────────────────┐
    │                     │
Keystream for         One-time MAC Key
Encryption                │
    │                     ↓
    │                ┌──────────┐
    │                │Poly1305  │
    │                │   MAC    │
    │                └──────────┘
    ↓                     ↓
Plaintext (P)        Auth Tag (T)
	│           
    │  XOR ⊕  
    ↓
Ciphertext (C)

Analogy: ChaCha20-Poly1305 is like a secure envelope with a tamper-evident seal - ChaCha20 seals the contents (encryption), and Poly1305 provides the tamper-evident seal (authentication).

ChaCha20 Performance and Security

Performance

  • Very fast in pure software
  • Outperforms AES without hardware acceleration
  • Ideal for mobile, IoT, ARM devices

Security Advantages

  • Constant-time operations → resistant to timing attacks
  • No S-boxes, no lookup tables
  • Long keystream period (512-bit internal state)

Real-World Usage

  • ChaCha20-Poly1305 (AEAD) is the standard combination
  • Used in modern protocols:
    • TLS 1.3
    • QUIC
    • WireGuard VPN
    • SSH

CRITICAL RULE ⚠️

  • Nonce reuse = total security break
  • Each (key, nonce) pair must be unique

Analogy: ChaCha20 is like a Formula 1 car optimized for speed on regular roads (software) rather than requiring a special racetrack (hardware acceleration like AES-NI).


Block Ciphers

Overview

  • Convert one block at a time
  • Block size is big enough to avoid known-plaintext attack
  • The block size of 64 or 128 bits is typical

Key Properties

  • The output should look random
  • No correlation between plaintext and ciphertext
    • Cannot compute ciphertext back to plaintext without having a key
  • Bit spreading can be:
    • Limited to one block, or
    • Distributed across blocks

Basic Operation


Block Cipher Features

1. Block Size

  • Larger block sizes mean greater security
  • Trade off with speed!

2. Key Size

  • Larger key size means greater security

3. Number of Rounds

  • Multiple rounds offer increasing security

4. Encryption Modes

  • Define how a message larger than the block size is encrypted

Analogy: Block ciphers are like processing documents page by page through a complex shredder and reassembler - each page (block) goes through multiple transformations (rounds) using your secret instructions (key).

อย่าง AES อันนี้เป็น Block Cipher นะ เพราะต้องแบ่ง Data เป็น size 128 bit อะไรก่อน (check??)


Mode of Operations

Overview

  • A message is broken into independent blocks of n bits
  • Some pad characters are filled in to make the last block complete
  • Block ciphers process data as blocks:
    • 64-bits for DES
    • 128-bits for AES (Block-size; not key size)
      • Because key in AES can be 128, 256, 512 blah blah

Standard Modes (FIPS SP800-38a)

  1. Electronic Code Book (ECB)
  2. Cipher Block Chaining (CBC)
  3. Cipher Feedback (CFB)
  4. Output Feedback (OFB)
  5. Counter Mode (CTR)

AES can be processed, triggered in ECB, CBC, CFB, OFB, CTR, and we should know each modes and how it works.


AES Block and Key Sizes

AES Variants

AES VariantKey SizeBlock Size
AES-128128 bits128 bits
AES-192192 bits128 bits
AES-256256 bits128 bits

AES-XXX XXX คือ เลขของ Key Size ไม่ว่าจะเลขไหน Block size จะเป็น 128 bits เท่าเดิม

Number of Rounds

VariantRounds
AES-12810 rounds
AES-19212 rounds
AES-25614 rounds

Note: Regardless of key size, AES always uses a 128-bit block size.


Electronic Codebook (ECB)

Description

  • The simplest mode
  • Split a plaintext message into blocks
  • Encrypt each block using the same key
  • Have a unique ciphertext value for each plaintext block

Encryption/Decryption

Encryption: Ci=Ek(xi)\boxed{\text{Encryption: } C_i = E_k(x_i)}
Decryption: xi=Dk(Ci)\boxed{\text{Decryption: } x_i = D_k(C_i)}

Architecture

Security Issues ⚠️

  • NOT secure for long messages since repeated plaintext is seen in repeated ciphertext
  • Reordering ciphertext determines reordered plaintext
  • Reveals patterns in plaintext

Advantages

  • Errors in one block do NOT propagate to other blocks
  • Blocks can be encrypted in parallel

Famous Example: ECB Penguin

  • Original image → Encrypted with ECB → Shows visible penguin outline
  • This demonstrates that ECB preserves patterns

Analogy: ECB is like using the same simple substitution cipher for every word in a book - patterns become obvious, and you can see repeated words even though they're "encrypted."


Cipher Block Chaining (CBC)

Description

  • The next input depends on the previous output
  • Repeated text gets mapped to different encrypted data
  • Needs an Initialization Vector (IV) which must be known by both sender and receiver

Encryption/Decryption Formulas

Encryption: Ci=Ek(xi⊕Ci−1), with C0=IV\boxed{\text{Encryption: } C_i = E_k(x_i \oplus C_{i-1}), \text{ with } C_0 = IV}
Decryption: xi=Ci−1⊕Dk(Ci), with C0=IV\boxed{\text{Decryption: } x_i = C_{i-1} \oplus D_k(C_i), \text{ with } C_0 = IV}

Architecture

Encryption & Decryption:

IV = Initialization vector (random number)

Advantages ✓

  • Repeated text gets mapped to different encrypted data
  • More secure than ECB

Disadvantages ✗

  • Errors in one block propagate to another block
    • Provide error propagation
  • Encryption must be sequential (cannot parallelize)

Important Property

  • Decryption CAN be parallelized ✓
    • Each DK(Ci)D_K(C_i) is independent
    • Only needs Ci−1C_{i-1}, which is already available
    • All DK(Ci)D_K(C_i) operations can be done in parallel

Analogy: CBC is like a chain reaction - each encrypted block depends on the previous one, making patterns disappear. Think of it like mixing paint where each new color depends on the previous mixture.


CBC Parallelization

CBC Encryption (Sequential ✗ parallel)

Encryption rule:
Ci=EK(Pi⊕Ci−1)C_i = E_K(P_i \oplus C_{i-1})

  • Each block depends on the previous ciphertext block
  • You cannot encrypt block ii until Ci−1C_{i-1} is known
  • ⇒ Encryption is inherently sequential

CBC Decryption (Parallelizable ✓)

Decryption rule:
Pi=DK(Ci)⊕Ci−1P_i = D_K(C_i) \oplus C_{i-1}

  • Each DK(Ci)D_K(C_i) is independent
  • Only needs Ci−1C_{i-1}, which is already available
  • ⇒ All DK(Ci)D_K(C_i) operations can be done in parallel

After decryption, each result is XORed with its corresponding Ci−1C_{i-1}.

The Bit Flipping Attack on CBC

Vulnerability

If you know the position of the target byte, then you can modify the corresponding ciphertext position in the previous ciphertext block.

How it Works

  • If you modify a byte in the ciphertext Ci−1C_{i-1}, then PiP_i will be changed by one block
  • Ci−1C_{i-1} only affects the plaintext PiP_i by ⊕\oplus

Visual Example

Impact

  • Red case: A ciphertext byte of C2C_2 modified
    • Affects the corresponding byte in the next plaintext block P3P_3
    • The corresponding full plaintext block P2P_2 becomes garbage
  • Green case: An IV byte is modified
    • Affects only the corresponding byte in the first plaintext P1P_1
    • If the target plaintext is in the first block, this will not leave a trace

Analogy: Flipping a bit in CBC is like changing one ingredient in a recipe - it affects the current dish (making it garbage) and slightly changes the next dish in the sequence.

CBC vs ECB

Advantage of CBC over ECB

  • Changing IV results in different ciphertext for identical message
  • Provides better security against pattern analysis

Drawback of CBC

  • The error in transmission gets propagated to few further blocks during decryption due to chaining effect

Message Authentication Code (MAC)

Definition

A message authentication code (MAC) is a cryptographic checksum on data that uses a session key to detect both accidental and intentional modifications of the data.

Requirements

A MAC requires two inputs:

  1. A message
  2. A secret key known only to the originator of the message and its intended recipient(s)

MAC Process

Analogy: A MAC is like a tamper-evident seal on a package that only you and the recipient know how to create - if the seal is broken or different, you know someone tampered with it.

The message is NOT encrypted at all; so it’s covered only I (integrity) in CIA
ถ้าต้องการ Confidentiality ก็ต้อง encrypt ก่อนส่งด้วยน้า

Attack on CBC-MAC

Vulnerability

CBC is vulnerable to CPA (Chosen Plaintext Attack)!

CBC-MAC (CBC Message Authentication Code)

  • Used to construct the MAC for proving that message is not changed and comes from stated sender

What is CPA?

Chosen Plaintext Attack (CPA) is a model for cryptanalysis which assumes that the attacker can choose random plaintexts to be encrypted and obtain the corresponding ciphertexts.

Why is CBC Vulnerable to CPA?

1. Predictable XOR Dependency

It’s done easily by XOR, ถ้าไปดู XOR attack ก็จะเห็นว่ามันกาก

In CBC mode, each plaintext block PnP_n is XORed with the previous ciphertext block Cn−1C_{n-1} before encryption:

Cn=Ek(Pn⊕Cn−1)C_n = E_k(P_n \oplus C_{n-1})

  • If an attacker can choose plaintexts and observe the corresponding ciphertexts, they can manipulate the XOR operation to learn information about the encryption

2. IV Manipulation Attack (CPA Variant)

The first block of CBC mode uses an Initialization Vector (IV):

C1=Ek(P1⊕IV)C_1 = E_k(P_1 \oplus IV)

  • If the attacker chooses different IVs while encrypting the same plaintext, they can extract partial information about the plaintext through statistical analysis

3. Blockwise Decryption Using CPA

Since decryption in CBC mode is:

Pn=Dk(Cn)⊕Cn−1P_n = D_k(C_n) \oplus C_{n-1}

  • If the attacker can alter ciphertext blocks and observe decrypted values (such as through error messages in padding oracle attacks), they can recover plaintext block-by-block

CPA Exploit Example: Padding Oracle Attack

One of the most famous CPA attacks on CBC is the Padding Oracle Attack, where:

  1. The attacker modifies a ciphertext block and sends it to a server that decrypts it
  2. If the server returns an error message based on padding correctness, the attacker can infer whether the decrypted plaintext has valid padding
  3. By carefully modifying bytes, the attacker can decrypt each byte of the plaintext without knowing the encryption key

How to Prevent CPA Attacks on CBC?

1. Use Random IVs

  • Ensure that the IV is unpredictable and different for every encryption

2. Authenticate the Ciphertext (Use MAC)

  • CBC does not provide integrity protection
  • Use ==Encrypt-then-MAC (EtM)== or modern alternatives

3. Move to Modern Encryption

Use AES-GCM (Galois/Counter Mode) or ChaCha20-Poly1305:

  • These ciphers provide encryption and authentication together
  • They are AEAD (Authenticated Encryption with Associated Data) schemes

Analogy: CBC's CPA vulnerability is like a lock that, if you can try different keys and see partial feedback (like "almost correct"), you can eventually deduce the right key. Modern AEAD modes are like smart locks that give no feedback at all.

AES-GCM Encryption Process #Recall

1. Nonce (IV) Generation

  • A unique Initialization Vector (IV) is chosen for each encryption

2. AES-CTR Encryption

  • AES runs in Counter (CTR) mode, generating a keystream for encryption
  • Plaintext is XORed with the keystream to produce the ciphertext

3. GMAC (Authentication Tag Calculation)

A cryptographic MAC (GMAC) is calculated over:

  • The ciphertext
  • Additional authenticated data (AAD) (if provided)
  • The IV and other metadata

The tag ensures data integrity

Architecture

Secret Key (256-bit)
         ↓
    ┌────────────────┐
    │    ChaCha20    │
    │(Block Function)│
    └────────────────┘
         ↓
    Keystream for         One-time MAC Key
    Encryption                 ↓
         ↓                 ┌──────────┐
         │                 │Poly1305  │
         │                 │   MAC    │
         │                 └──────────┘
         ↓                      ↓
    Plaintext (P)         Auth Tag (T)
         ↓
       XOR
         ↓
    Ciphertext (C)

AES-GCM Decryption Process

1. Recompute the Authentication Tag

  • If the computed tag doesn't match the received tag, decryption fails
  • This protects against tampering attacks

2. AES-CTR Decryption

  • The ciphertext is decrypted using the same AES-CTR keystream

Analogy: AES-GCM is like sending a locked box with a tamper-evident seal - the lock (encryption) keeps contents secret, and the seal (GMAC) ensures no one tampered with it.


Cipher Feedback (CFB)

Description

  • It converts a block cipher into a stream cipher
  • The IV is encrypted first to generate an output block
  • The message is XORed with the feedback of encrypting the previous block
  • The ciphertext is fed back into the next encryption step (instead of plaintext blocks like CBC)

Key Features

  • Does not require padding, since it encrypts small segments (e.g., 8-bit, 128-bit, etc.)
  • Can vary the number of bits fed back, trading off efficiency for ease of use
  • Errors propagate for several blocks after the error, but the mode is self-synchronizing (as CBC)

Requirements

  • Needs an IV which must be known by both sender & receiver
    • How to distribute the IV?
  • Decreased throughput

CFB Architecture

s-bit CFB Mode:

The diagram shows encryption and decryption using a shift register approach where only s bits (not the full block) are processed at a time.

Analogy: CFB is like CBC but works on smaller chunks - instead of processing full pages (blocks), it processes lines (segments), making it more flexible but slightly slower.

How is Cipher Feedback Used?

If CFB mode is used within the encryption algorithm, it's often used to encrypt the following services:

  • Wi-Fi communications
  • Secure websites
  • Chip-based security
  • File encryption
  • Secure Sockets Layer or Transport Layer Security encrypted virtual private network tunnels
  • Simple Mail Transfer Protocol email
  • Messaging services based on the Extensible Messaging and Presence Protocol
  • Secure FTP
  • Secure Shell
  • Voice over IP

CBC vs CFB

(1) Unit Size Difference

CFB:

  • Data is encrypted in units that are smaller than a predefined block size cipher unit (usually 64 bits)
  • CFB encrypts units in 1- or 2-byte (8- or 16-bit) block sizes
  • Processes each bit at a time as opposed to the entire 64 bits
  • No padding process is needed when the data size is less than 64 bits

CBC:

  • Processes full blocks (e.g., 64 bits)
  • Requires padding if message doesn't align with block size

(2) Encryption Method Difference

CFB:

  • Unlike CBC, which directly encrypts plaintext blocks, CFB encrypts the previously encrypted plaintext block and then adds this to the next plaintext block
  • This means that the same algorithm used to encrypt the data can be used to decrypt it, which simplifies the decryption process

CBC:

  • Directly encrypts plaintext blocks after XORing with previous ciphertext

Analogy: CBC is like painting a wall in large sections, while CFB is like painting it stroke by stroke - more flexible but takes more individual steps.


Output Feedback (OFB)

Description

  • Similar to CFB, but feedback is from the output of the block cipher and independent of the message
  • No error propagation
    • Why? ลองดู C2C_2 มัน independent จาก C1C_1 ถูกป้ะ ดังนั้นก็เลย NO ERROR PROPAGATION
    • If there’s an error with C1C_1, C2C_2 will be just fine.

Key Difference from CFB

  • In CFB: The ciphertext is fed back into the encryption
  • In OFB: The encrypted IV/output is fed back (independent of plaintext/ciphertext)

OFB Architecture

Encryption & Decryption:

Advantages

  • No error propagation - if one ciphertext bit is corrupted, only the corresponding plaintext bit is affected
  • Can pre-compute the keystream before the message arrives

Disadvantages

  • If keystream repeats (same IV reused), security breaks completely

Analogy: OFB is like a random number generator running independently - it creates a stream of random-looking numbers that you XOR with your message. The generator doesn't care what your message is, making it more predictable if misused.


Counter Mode (CTR)

Description

  • Sender and receiver share a counter (does not need to be secret) and the secret key
  • PiP_i is the n first bytes of the i-th block of the plain packet, where 1≤n≤block_size1 \leq n \leq \text{block\_size}
  • Trunc(x,y)\text{Trunc}(x,y) function truncates the x first bytes of the y value

Encryption/Decryption Formulas

Encryption: Ci=Pi⊕Enc(counter+i)\boxed{\text{Encryption: } C_i = P_i \oplus \text{Enc}(\text{counter} + i)}
Decryption: Pi=Trunc(n,Ci⊕Enc(counter+i))\boxed{\text{Decryption: } P_i = \text{Trunc}(n, C_i \oplus \text{Enc}(\text{counter} + i))}

CTR Mode Architecture

Encryption & Decryption:

เห็นป้ะ อันนี้สามารถ Encrypt/Decrypt Parallel ได้เลยอะ ไม่พึ่งใครเท่านั้น

Analogy: CTR mode is like having a deterministic random number generator - you start at a number (counter), increment it, encrypt it, and XOR with your message. It's simple, fast, and parallelizable.

CTR Mode Advantages

1. Software and Hardware Efficiency

  • Different blocks can be encrypted in parallel

2. Preprocessing

  • The encryption part can be done offline
    • พาร์ทข้างบนทั้งหมดก่อนถึง XOR ไง
  • When the message is known, just do the XOR

3. Random Access

  • The encryption of a block can be done in random order
  • Very useful for hard-disk encryption

4. Security

  • Same as CBC, CFB, OFB modes

5. Simplicity

  • Uses only the encryption function of the cipher (e.g., AES) for both encryption and decryption
  • For ECB, CBC modes, decryption function is required and it is more costly than encryption

6. Messages of Arbitrary Length

  • The ciphertext is the same length as the plaintext

7. Performance

  • A bit faster than CBC, CFB or OFB since the keystream can be precomputed and parallelizable operated

Analogy: CTR mode is like a factory assembly line where each worker (processor) can work on different parts simultaneously, making it ideal for modern parallel computing.


Initialization Vector (IV)

Purpose

  • All modes (except ECB) require an initialization vector
  • A sort of dummy block to kick off the process for the first real block
  • Also provides some randomization for the process

Security Requirements

  • No need for the IV to be secret
  • Important: It is never reused with the same key

Consequences of IV Reuse

  • For CBC and CFB: Reusing an IV leaks some information
  • For OFB and CTR: Reusing an IV completely destroys the security

Analogy: The IV is like the starting position for a shuffle - it doesn't need to be secret, but using the same starting position twice with the same deck defeats the purpose of shuffling.


Padding

When Padding is NOT Required

  • CTR, OFB or CFB mode - padding is not required
  • In these cases, the ciphertext is always the same length as the plaintext
  • A padding method is not applicable

When Padding IS Required

  • A block cipher works on units of a fixed size
  • But messages come in a variety of lengths
  • Examples: ECB, CBC
  • Need to pad the final block

Padding Schemes

1. Simple: Null Padding

  • Simply pad with null bytes

2. DES Method

  • Add a single one bit
  • Followed by enough zero bits to fill out the block
  • If the message ended on a block boundary, a whole padding block will be added

3. Ciphertext Stealing (Obsolete)

CBC Padding Issue

Historical Context

CBC padding techniques such as PKCS#7 are still present in legacy systems but are discouraged today because they are vulnerable to padding oracle attacks.

Modern Recommendation

Modern cryptographic standards recommend authenticated encryption modes that eliminate padding entirely.

Modern Solution: AEAD

  • Modern systems use AEAD (Authenticated Encryption with Associated Data)
  • Examples: AES-GCM, CTR

Why AEAD Doesn't Need Padding

Core Idea

Ciphertext=Plaintext⊕Keystream\text{Ciphertext} = \text{Plaintext} \oplus \text{Keystream}

  • AEAD modes do not encrypt plaintext blocks directly
  • Instead, they work like stream ciphers
  • You can XOR any number of bytes
    • No block alignment needed
    • No padding needed

Analogy: Traditional block ciphers with padding are like packing boxes that must be completely full - you add packing material to fill gaps. Stream ciphers (and AEAD modes) are like shrink-wrap that conforms to any shape perfectly.


Mode Comparison Summary

ModeDescriptionTypical Application
Electronic Codebook (ECB)Each block of 64 plaintext bits is encoded independently using the same key.• Secure transmission of single values (e.g., an encryption key)
Cipher Block Chaining (CBC)The input to the encryption algorithm is the XOR of the next 64 bits of plaintext and the preceding 64 bits of ciphertext.• General-purpose block-oriented transmission
• Authentication
Cipher Feedback (CFB)Input is processed s bits at a time. Preceding ciphertext is used as input to the encryption algorithm to produce pseudorandom output, which is XORed with plaintext to produce next unit of ciphertext.• General-purpose stream-oriented transmission
• Authentication
Output Feedback (OFB)Similar to CFB, except that the input to the encryption algorithm is the preceding DES output.• Stream-oriented transmission over noisy channel (e.g., satellite communication)
Counter (CTR)Each block of plaintext is XORed with an encrypted counter. The counter is incremented for each subsequent block.• General-purpose block-oriented transmission
• Useful for high-speed requirements

Advantages of Block Ciphers

  1. Have longer cryptanalytic history
  2. Are highly versatile (flexibility)
  3. Fit standardization and compliance
  4. Benefit from hardware acceleration
  5. Support clean security proofs
  6. Fail more gracefully under misuse

Even Stream Ciphers is faster, but we still use Block Ciphers because of these above-mentioned reasons!

Analogy: Block ciphers are like well-established recipes that have been tested by millions - they might require more preparation (padding, modes), but their reliability and widespread support make them the standard choice for most applications.


Summary

Stream Ciphers

  • Fast, simple, continuous processing
  • Examples: RC4 (deprecated), ChaCha20 (modern)
  • No padding needed
  • Good for: real-time communications, low-latency applications

Block Ciphers

  • Process fixed-size blocks
  • Require modes of operation
  • Examples: AES (128-bit blocks)
  • Good for: file encryption, disk encryption, general-purpose encryption

Modern Recommendations

  • For stream encryption: ChaCha20-Poly1305
  • For block encryption: AES-GCM
  • Avoid: ECB mode (always), RC4 (deprecated), CBC without proper IV management

Key Takeaways

  1. Never reuse IVs/nonces with the same key
  2. Use AEAD modes for new applications (AES-GCM, ChaCha20-Poly1305)
  3. Padding oracle attacks make CBC dangerous without careful implementation
  4. Parallelization matters - CTR and GCM can process blocks in parallel