Skip to main content
Classical Ciphers: Caesar, Vigenere, XOR & Frequency Analysis
Lesson 3 of 16

Classical Ciphers: Caesar, Vigenere, XOR & Frequency Analysis

Implement and break Caesar, Affine, Vigenere, Rail Fence, and repeating-key XOR ciphers in Python 3 using frequency analysis, Index of Coincidence, and the Kasiski test.

Beginner 28 min Cryptography

Learning objectives

  • Compare monoalphabetic substitution, polyalphabetic substitution, transposition, and XOR ciphers
  • Implement Caesar, ROT13, Affine, Vigenere, Rail Fence, and XOR routines using modular arithmetic in Python 3
  • Distinguish monoalphabetic from polyalphabetic ciphertexts using letter frequencies and Index of Coincidence
  • Estimate repeating key lengths with the Kasiski test and recover plaintext without knowing the key

Recommended first: Math Foundations: Modular Arithmetic, GCD & Congruences

#Why this matters

Classical ciphers were built for paper and early mechanical rotors rather than modern CPUs. None are safe for real-world secrecy today, yet they teach the exact foundations behind modern cryptography (modular inverses, confusion, key reuse) and appear constantly in CTF challenges and legacy audits.

Learning to identify and break classical ciphers in Python 3 sharpens your statistical intuition and helps you spot structural leaks in ciphertext.

#Substitution vs. transposition ciphers

Classical ciphers replace symbols (substitution), shuffle positions (transposition), or combine both.

Substitution vs. Transposition Ciphers
Substitution (Caesar, Affine, Simple, Vigenere)
  • Replaces plaintext letters with other letters
  • Monoalphabetic forms preserve frequency shape
  • Polyalphabetic forms flatten frequency spikes
Transposition (Rail Fence, Columnar)
  • Keeps original letters unchanged, alters only order
  • Always preserves exact plaintext letter frequencies
  • Broken by testing rail counts or column widths
  • Caesar and ROT13: Maps A = 0..Z = 25 with E(x) = (x + k) mod 26 and D(x) = (x - k) mod 26. With only 25 shifts, brute force is instant. ROT13 (k = 13) is self-inverse because (x + 13 + 13) mod 26 = x.
  • Affine cipher: Uses E(x) = (a * x + b) mod 26 and D(x) = a^(-1) * (x - b) mod 26. Unique decryption requires GCD(a, 26) = 1, leaving 12 valid a values (1, 3, 5, 7, 9, 11, 15, 17, 19, 21, 23, 25) and 12 * 26 = 312 keys. With a = 5, b = 8, HELLO becomes RCLLA (pow(5, -1, 26) = 21).
  • Simple substitution: Permutes the alphabet (26! or ~4 x 10^26 keys). Because each plaintext letter always maps to one ciphertext letter, frequency analysis breaks long messages quickly.
  • Rail Fence transposition: Writes characters diagonally across r rails in a zigzag wave and reads row by row. With rails = 3, HELLOWORLD becomes HOLELWRDLO and WEAREDISCOVEREDFLEEATONCE becomes WECRLTEERDSOEEFEAOCAIVDEN.
  • Other CTF staples: Atbash reverses the alphabet, Playfair swaps digrams in a 5x5 grid, and Bacon encodes letters as 5-symbol A/B strings.

#Vigenere and repeating-key XOR

The Vigenere cipher shifts each letter by a repeating keyword: E(p_i, k_i) = (p_i + k_i) mod 26, flattening single-letter spikes. With key KEY, ATTACK AT DAWN encrypts to KXRKGI KX BKAL.

Repeating-key XOR generalizes Vigenere to raw bytes: c_i = p_i ^ k_(i mod L). XOR is self-inverse ((p ^ k) ^ k = p), so encryption and decryption are identical, yet short repeating keys break per slice via frequency scoring.

python
def caesar_encrypt(text, shift):
    return "".join(chr((ord(c) - 65 + shift) % 26 + 65) if c.isalpha() else c for c in text.upper())

def affine_decrypt(text, a, b):
    inv = pow(a, -1, 26)  # ValueError if GCD(a, 26) != 1
    return "".join(chr(inv * (ord(c) - 65 - b) % 26 + 65) if c.isalpha() else c for c in text.upper())

def vigenere_encrypt(text, key):
    key, out, ki = key.upper(), [], 0
    for c in text.upper():
        if c.isalpha():
            out.append(chr((ord(c) - 65 + ord(key[ki % len(key)]) - 65) % 26 + 65))
            ki += 1
        else:
            out.append(c)
    return "".join(out)

def xor_bytes(data, key):
    return bytes(b ^ key[i % len(key)] for i, b in enumerate(data))

print(caesar_encrypt("HELLO", 13))               # URYYB
print(affine_decrypt("RCLLA", 5, 8))             # HELLO
print(vigenere_encrypt("ATTACK AT DAWN", "KEY")) # KXRKGI KX BKAL
print(xor_bytes(xor_bytes(b"CTF", b"K"), b"K"))  # b'CTF'

#Frequency analysis, Index of Coincidence, and the Kasiski test

English letter frequencies follow ETAOIN SHRDLU, with E at ~12.7%, T at ~9.1%, and A at ~8.2%. Monoalphabetic ciphers and transpositions preserve this shape.

To separate monoalphabetic from polyalphabetic ciphertexts, compute the Index of Coincidence (IC):

IC = sum(f_i * (f_i - 1)) / (N * (N - 1))

English and monoalphabetic texts score near 0.065, random text scores near 0.038, and Vigenere typically lands around 0.038 to 0.045.

When IC signals a polyalphabetic cipher, the Kasiski test takes the GCD of distances between repeated 3+ letter sequences to estimate candidate key lengths. If XYZ repeats at 12 and 42 (distance 30) and QRS at 19 and 34 (distance 15), GCD(30, 15) = 15 points to key length 15 (or a divisor like 5 or 3). Splitting into L slices reduces each slice to a Caesar cipher.

  1. Inspect AlphabetCheck character set (A-Z, A/B only, hex, or binary bytes)
  2. Measure ICNear 0.065 = monoalphabetic; 0.038-0.045 = polyalphabetic
  3. Estimate Key LengthRun Kasiski test or average IC per candidate slice length
  4. Solve SlicesApply Caesar brute force or ETAOIN frequency analysis per slice
  5. Verify PlaintextConfirm readable English words and expected flag format

#Automating cryptanalysis in Python 3

python
from collections import Counter
from functools import reduce
import math

def index_of_coincidence(text):
    letters = [c for c in text.upper() if c.isalpha()]
    n = len(letters)
    return sum(f * (f - 1) for f in Counter(letters).values()) / (n * (n - 1)) if n > 1 else 0.0

def kasiski_gcd(ciphertext, min_len=3):
    clean = "".join(c for c in ciphertext.upper() if c.isalpha())
    dists = [clean.find(clean[i:i + min_len], i + min_len) - i
             for i in range(len(clean) - min_len)
             if clean.find(clean[i:i + min_len], i + min_len) != -1]
    return reduce(math.gcd, dists) if dists else 0

#Defending / Common mistakes

  • Using classical ciphers or short-key XOR in production: Never obfuscate secrets with ROT13, Vigenere, or repeating XOR; use AES-256-GCM or ChaCha20-Poly1305.
  • Skipping IC before brute-forcing: Measure IC first so you do not waste time running Caesar or 1-to-1 frequency maps on polyalphabetic text.
  • Invalid Affine keys: Values with GCD(a, 26) != 1 (like 2, 4, 13) cause collisions and cannot be uniquely decrypted.
  • Trusting one Kasiski repeat: Verify candidate key lengths by checking whether average slice IC rises back near 0.065.

#Summary

  • Substitution ciphers replace letters while transposition ciphers (Rail Fence) reorder positions without changing letters.
  • Affine requires GCD(a, 26) = 1, ROT13 is self-inverse (k = 13), and repeating-key XOR is byte-level Vigenere.
  • Monoalphabetic ciphers preserve ETAOIN SHRDLU frequencies and IC ~0.065; polyalphabetic ciphers lower IC to 0.038-0.045.
  • Combining IC, the Kasiski test, and per-slice frequency analysis breaks classical ciphers systematically.

Lecture presentations

Slides on this topic: view them in the browser or download the PDF.

Classical Ciphers

Substitution and transposition methods

Slides: 24 PDF · 898 KB

Knowledge check

Sign in to take the test, complete lessons and save your progress. Log in

Practice: test your knowledge