#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.
- Replaces plaintext letters with other letters
- Monoalphabetic forms preserve frequency shape
- Polyalphabetic forms flatten frequency spikes
- 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 = 25withE(x) = (x + k) mod 26andD(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 26andD(x) = a^(-1) * (x - b) mod 26. Unique decryption requiresGCD(a, 26) = 1, leaving 12 validavalues (1, 3, 5, 7, 9, 11, 15, 17, 19, 21, 23, 25) and12 * 26 = 312keys. Witha = 5, b = 8,HELLObecomesRCLLA(pow(5, -1, 26) = 21). - Simple substitution: Permutes the alphabet (
26!or ~4 x 10^26keys). Because each plaintext letter always maps to one ciphertext letter, frequency analysis breaks long messages quickly. - Rail Fence transposition: Writes characters diagonally across
rrails in a zigzag wave and reads row by row. Withrails = 3,HELLOWORLDbecomesHOLELWRDLOandWEAREDISCOVEREDFLEEATONCEbecomesWECRLTEERDSOEEFEAOCAIVDEN. - Other CTF staples: Atbash reverses the alphabet, Playfair swaps digrams in a 5x5 grid, and Bacon encodes letters as 5-symbol
A/Bstrings.
#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.
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.
- Inspect AlphabetCheck character set (A-Z, A/B only, hex, or binary bytes)
- Measure ICNear 0.065 = monoalphabetic; 0.038-0.045 = polyalphabetic
- Estimate Key LengthRun Kasiski test or average IC per candidate slice length
- Solve SlicesApply Caesar brute force or ETAOIN frequency analysis per slice
- Verify PlaintextConfirm readable English words and expected flag format
#Automating cryptanalysis in Python 3
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(like2, 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 to0.038-0.045. - Combining IC, the Kasiski test, and per-slice frequency analysis breaks classical ciphers systematically.