Skip to content
Tutorials Center
My learning

Topics

Lesson 12 of 80 ยท Cryptography Basics

Symmetric Encryption and Modes

Understand block and stream ciphers, AES, why ECB leaks patterns, how CBC, CTR and GCM use IVs and nonces, and why authenticated encryption is the default.

Symmetric encryption uses one secret key to turn readable data (plaintext) into unreadable data (ciphertext), and the same key to turn it back. It is fast enough to protect everything from a disk drive to a video call, which is why it does the bulk of the work in TLS, VPNs, password managers and encrypted databases.

Using a good cipher is not enough. The same cipher, AES, can be used in a way that leaks your data's structure, allows an attacker to edit messages, or collapses completely after one mistake with a nonce. This lesson explains block and stream ciphers, what a mode of operation is, and why modern code should use authenticated encryption such as AES-GCM. If the vocabulary of encoding, encryption and hashing is new, start with Cryptography in Plain Language.

Python's standard library has no AES. Real projects use the cryptography package (or a vetted library in another language). The live demos below use a small toy block cipher built from HMAC so that you can run and inspect every mode in the browser. The toy is a stand-in to show the structure of modes. It is not secure and must never protect real data.

Block ciphers and stream ciphers

A block cipher encrypts fixed-size chunks. AES works on 128-bit (16-byte) blocks and accepts 128, 192 or 256-bit keys. On its own it is a keyed permutation: for each key, every possible block maps to exactly one other block, and the mapping can be reversed.

A stream cipher produces a long pseudo-random keystream from a key and a nonce, and XORs it with the plaintext byte by byte. ChaCha20 is the best-known modern example. A block cipher can be turned into a stream cipher by a mode such as CTR.

Real messages are rarely exactly one block long, so a block cipher needs a mode of operation that says how to handle many blocks. The mode matters as much as the cipher.

A toy block cipher for experiments

Our stand-in is a Feistel network: split the block into two halves and, for eight rounds, mix one half with a keyed function of the other. The round function here is HMAC-SHA-256. The structure is real (DES is a Feistel cipher); the tiny size and round function make it unsuitable for production.

Python A toy block cipher (stand-in for AES)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

The last line is the seed of a problem: for a fixed key, a block cipher is deterministic. Encrypt the same block twice and you get the same ciphertext twice. How the mode deals with that decides whether your data stays private.

ECB: the mode that leaks patterns

ECB (Electronic Codebook) encrypts every block independently with the same key. Identical plaintext blocks therefore give identical ciphertext blocks. The famous demonstration is an image of a penguin encrypted with ECB: the colors change, but the outline is still plainly visible. Any data with repeated blocks, such as images, database columns of the same value or padded fields, leaks its shape.

The next demo encrypts a small 16-by-8 character "image" in ECB and in CBC. Each row is exactly one block, so we can print a short prefix of each row's ciphertext:

Python ECB reveals patterns, CBC hides them

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

ECB shows only as many different ciphertext blocks as there are different rows, and the repeated rows are easy to spot. CBC produces eight different blocks even though the plaintext has repeats. Never use ECB for anything bigger than a single block of random data.

CBC, CTR and GCM

flowchart LR
    IV["IV (random)"] --> X1(("XOR"))
    P1["Plaintext block 1"] --> X1
    X1 --> E1["Encrypt"] --> C1["Ciphertext 1"]
    C1 --> X2(("XOR"))
    P2["Plaintext block 2"] --> X2
    X2 --> E2["Encrypt"] --> C2["Ciphertext 2"]

In CBC each plaintext block is XORed with the previous ciphertext block before encryption, so equal blocks no longer produce equal output.

CBC (Cipher Block Chaining) needs a random, unpredictable IV (initialization vector) per message. It needs padding to a whole number of blocks, and padding errors have caused serious attacks (padding oracles) when a server reveals whether decryption padding was valid. CBC also cannot detect modification by itself, and encryption cannot be parallelized.

CTR (Counter mode) turns the block cipher into a stream cipher. It encrypts a nonce plus a counter to produce keystream blocks and XORs them with the data. No padding is needed and it parallelizes well. Its rule is absolute: never use the same key and nonce for two messages.

GCM (Galois/Counter Mode) is CTR plus a built-in authentication tag. It is the standard choice (AES-GCM, and ChaCha20-Poly1305 as the alternative). A nonce (also called IV in GCM) is a number used once; for GCM it is typically 12 bytes. It does not need to be secret, only unique per key. Random 96-bit nonces are fine for a limited number of messages per key; at very high volume use a counter and rotate keys.

Nonce reuse destroys CTR

In any stream-like mode, ciphertext equals plaintext XOR keystream. If two messages use the same keystream, XORing the two ciphertexts cancels the keystream and leaves plaintext1 XOR plaintext2. If an attacker knows or guesses one message, the other falls out immediately:

Python What nonce reuse gives away

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

This is not a theoretical weakness. Reused nonces have broken Wi-Fi encryption (WPA2 key reinstallation) and many home-made protocols. In GCM it is even worse, because a repeated nonce also leaks the authentication key.

Encryption is not authentication

Plain CTR and CBC give confidentiality but not integrity. An attacker who cannot read the message can still change it. In CTR, flipping a bit in the ciphertext flips exactly the same bit in the plaintext. The final demo shows the attack, and then the fix: encrypt, then compute a MAC over the nonce, associated data and ciphertext (the "encrypt-then-MAC" recipe, which GCM does internally). The MAC part is the HMAC you learned in HMAC and Message Authentication.

Python Bit-flipping, and authenticated encryption as the fix

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

The associated data (aad) is data that stays in the clear, like a header or invoice number, but is still covered by the tag. Changing it, or moving the ciphertext into a different context, makes decryption fail.

With a real library, you get all of this in a few lines. This snippet is read-only because the cryptography package is not available in the in-browser runner:

Python
import os
from cryptography.hazmat.primitives.ciphers.aead import AESGCM

key = AESGCM.generate_key(bit_length=256)    # keep in a secrets manager
aead = AESGCM(key)

nonce = os.urandom(12)                        # 96-bit nonce, unique per message
blob = aead.encrypt(nonce, b"PAY 0100 TO ALICE", b"invoice-77")

# store nonce + blob; blob ends with a 16-byte authentication tag
message = aead.decrypt(nonce, blob, b"invoice-77")   # raises InvalidTag if altered

A practical checklist

  • Prefer AES-256-GCM or ChaCha20-Poly1305 through a high-level AEAD API. Do not assemble modes and MACs yourself in production.
  • Generate keys with a cryptographic random source and store them in a key manager (see Randomness, Key Management and Secrets).
  • Never reuse a nonce with the same key. Store the nonce next to the ciphertext.
  • Never use ECB, and avoid unauthenticated CBC/CTR.
  • Encrypted data still needs integrity and access control. Encryption does not hide message length or who talked to whom.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Why is ECB mode considered insecure for general data?

    ECB encrypts every block independently, so repeated blocks show up as repeated ciphertext and reveal the structure of the data, as in the encrypted penguin picture.
  2. 2. What is the most important rule for a nonce in CTR or GCM mode?

    A nonce only has to be unique, not secret. Reusing it repeats the keystream, which lets an attacker XOR two ciphertexts to cancel it.
  3. 3. What does authenticated encryption (AEAD) add to plain encryption?

    An AEAD mode such as GCM produces a tag that is verified before any plaintext is released. Tampering makes decryption fail.
  4. 4. An attacker flips one bit of a CTR-encrypted message. What happens to the decrypted text without a MAC?

    CTR XORs a keystream into the data, so a changed ciphertext bit changes exactly the same plaintext bit. That is malleability, and why integrity protection is required.
  5. 5. Which is the best choice for new applications that need to encrypt data?

    Use a standard AEAD cipher from a well-reviewed library. ECB leaks patterns, XOR ciphers are trivially broken, and a fixed IV removes the protection CBC needs.

Summary

  • Symmetric encryption uses one shared key. AES is a block cipher; ChaCha20 is a stream cipher.
  • A block cipher needs a mode. ECB leaks patterns; CBC needs random IVs and padding; CTR and GCM turn the cipher into a stream and need unique nonces.
  • Reusing a nonce with the same key repeats the keystream and can expose messages or authentication keys.
  • Confidentiality alone lets attackers modify ciphertext. Use authenticated encryption (AES-GCM, ChaCha20-Poly1305) so tampering is detected before decryption.
  • The toy cipher in this lesson shows how modes work; real systems must use vetted libraries.

Next: Public-Key Cryptography, which solves the problem of sharing the key in the first place.