ποΈ Foundational Cryptosystems, Modular Groups & Cryptanalytic Techniques
Modern symmetric block ciphers like AES and public-key systems like RSA trace their mathematical lineage directly back to Classical Cryptography. Classical ciphers fall into two fundamental structural transformations: Substitution (where characters or blocks are replaced by other characters according to mathematical mappings) and Transposition (where the character identities remain constant while their physical positions are permuted). Understanding these early systems reveals Claude Shannon's dual concepts of Confusion (obscuring the relationship between the key and ciphertext) and Diffusion (spreading the statistical influence of individual plaintext letters across the ciphertext). Furthermore, study of classical schemes introduces the discipline of Cryptanalysis: breaking ciphers through statistical linguistics, the Index of Coincidence (IoC), the Kasiski Examination, and brute-force key-space exhaustion, demonstrating why monoalphabetic ciphers are vulnerable to frequency analysis and establishing the design principles of modern cryptography.
TAXONOMY OF CLASSICAL CRYPTOSYSTEMS:
CLASSICAL CIPHERS
β
ββββββββββββββββββββββββββββ΄βββββββββββββββββββββββββββ
βΌ βΌ
SUBSTITUTION CIPHERS TRANSPOSITION CIPHERS
(Replaces characters; alters identities) (Permutes positions; retains frequencies)
β β
ββββββββββ΄βββββββββ¬βββββββββββββββββββ ββββββββββ΄βββββββββ
βΌ βΌ βΌ βΌ βΌ
MONOALPHABETIC POLYGRAPHIC POLYALPHABETIC RAIL FENCE CIPHER COLUMNAR TRANSPOSITION
⒠Caesar Cipher ⒠Playfair (2x2) ⒠Vigenère (Zig-zag rails) (Keyed/unkeyed matrix perm)
β’ Affine Cipher β’ Hill Cipher β’ Beaufort
β’ Atbash Cipher (Linear algebra)β’ Autokey Cipher
MATHEMATICAL FOUNDATIONS OVER MODULAR RING Z_26:
β’ Alphabet Mapping: A=0, B=1, C=2, ..., Z=25
β’ Congruence: a β‘ b (mod m) <==> m divides (a - b)
β’ Additive Inverse: -a mod 26 = (26 - (a mod 26)) mod 26
β’ Multiplicative Inverse: a * a^(-1) β‘ 1 (mod 26) exists iff gcd(a, 26) = 1
Coprimes to 26: {1, 3, 5, 7, 9, 11, 15, 17, 19, 21, 23, 25} (Euler's Totient phi(26) = 12)
import math
def extended_gcd(a: int, b: int):
"""Returns (gcd, x, y) such that a*x + b*y = gcd"""
if a == 0:
return b, 0, 1
gcd, x1, y1 = extended_gcd(b % a, a)
x = y1 - (b // a) * x1
y = x1
return gcd, x, y
def mod_inverse(a: int, m: int = 26) -> int:
"""Computes multiplicative inverse of a modulo m using Extended Euclidean Algorithm."""
gcd, x, _ = extended_gcd(a, m)
if gcd != 1:
raise ValueError(f"Modular inverse does not exist: gcd({a}, {m}) = {gcd} != 1")
return (x % m + m) % m
class AffineCipher:
"""
Encryption: C = (a * P + b) mod 26
Decryption: P = a^(-1) * (C - b) mod 26
Constraint: gcd(a, 26) must be 1.
"""
def __init__(self, a: int, b: int):
if math.gcd(a, 26) != 1:
raise ValueError(f"Invalid key 'a'={a}. Must be coprime to 26.")
self.a = a
self.b = b
self.a_inv = mod_inverse(a, 26)
def encrypt(self, plaintext: str) -> str:
result = []
for char in plaintext.upper():
if char.isalpha():
p = ord(char) - ord('A')
c = (self.a * p + self.b) % 26
result.append(chr(c + ord('A')))
else:
result.append(char)
return "".join(result)
def decrypt(self, ciphertext: str) -> str:
result = []
for char in ciphertext.upper():
if char.isalpha():
c = ord(char) - ord('A')
p = (self.a_inv * (c - self.b)) % 26
result.append(chr(p + ord('A')))
else:
result.append(char)
return "".join(result)
# --- Verification & Execution ---
if __name__ == "__main__":
# Key a=5 (coprime to 26), b=8
cipher = AffineCipher(a=5, b=8)
msg = "CYBERSECURITY"
ciphertext = cipher.encrypt(msg)
decrypted = cipher.decrypt(ciphertext)
print(f"[*] Plaintext : {msg}")
print(f"[*] Key Parameters : a={cipher.a}, b={cipher.b}, a_inv={cipher.a_inv}")
print(f"[+] Affine Ciphertext: {ciphertext}")
print(f"[β] Recovered Text : {decrypted}")
assert decrypted == msg, "Decryption failure in Affine Cipher!"
class PlayfairCipher:
def __init__(self, key: str):
self.matrix, self.char_positions = self._build_matrix(key)
def _build_matrix(self, key: str):
key_sanitized = key.upper().replace('J', 'I')
used = set()
sequence = []
for char in key_sanitized:
if char.isalpha() and char not in used:
used.add(char)
sequence.append(char)
for code in range(ord('A'), ord('Z') + 1):
char = chr(code)
if char == 'J':
continue
if char not in used:
used.add(char)
sequence.append(char)
matrix = [sequence[i:i + 5] for i in range(0, 25, 5)]
positions = {}
for r in range(5):
for c in range(5):
positions[matrix[r][c]] = (r, c)
return matrix, positions
def _prepare_plaintext(self, text: str) -> list:
clean = [c for c in text.upper().replace('J', 'I') if c.isalpha()]
digraphs = []
i = 0
while i < len(clean):
char1 = clean[i]
if i + 1 < len(clean):
char2 = clean[i + 1]
if char1 == char2:
digraphs.append((char1, 'X'))
i += 1
else:
digraphs.append((char1, char2))
i += 2
else:
digraphs.append((char1, 'X'))
i += 1
return digraphs
def encrypt(self, plaintext: str) -> str:
digraphs = self._prepare_plaintext(plaintext)
cipher_digraphs = []
for c1, c2 in digraphs:
r1, col1 = self.char_positions[c1]
r2, col2 = self.char_positions[c2]
if r1 == r2: # Same row: Shift right
cipher_digraphs.append(self.matrix[r1][(col1 + 1) % 5])
cipher_digraphs.append(self.matrix[r2][(col2 + 1) % 5])
elif col1 == col2: # Same column: Shift down
cipher_digraphs.append(self.matrix[(r1 + 1) % 5][col1])
cipher_digraphs.append(self.matrix[(r2 + 1) % 5][col2])
else: # Rectangle rule: Swap columns
cipher_digraphs.append(self.matrix[r1][col2])
cipher_digraphs.append(self.matrix[r2][col1])
return "".join(cipher_digraphs)
if __name__ == "__main__":
playfair = PlayfairCipher("MONARCHY")
pt = "INSTRUMENTS"
ct = playfair.encrypt(pt)
print("[*] 5x5 Key Matrix ('MONARCHY'):")
for row in playfair.matrix:
print(" " + " ".join(row))
print(f"[*] Prepared Digraphs : {playfair._prepare_plaintext(pt)}")
print(f"[+] Playfair Ciphertext: {ct}")
import math
def mod_inv(a: int, m: int = 26) -> int:
a = a % m
for x in range(1, m):
if (a * x) % m == 1:
return x
raise ValueError(f"No inverse for {a} modulo {m}")
class HillCipher2x2:
"""
Encrypts vector P = [p1, p2]^T via C = K * P mod 26
Decrypts vector C via P = K^(-1) * C mod 26
Matrix Invertibility Requirement: gcd(det(K), 26) == 1
"""
def __init__(self, k11: int, k12: int, k21: int, k22: int):
self.k11 = k11 % 26
self.k12 = k12 % 26
self.k21 = k21 % 26
self.k22 = k22 % 26
det = (self.k11 * self.k22 - self.k12 * self.k21) % 26
if math.gcd(det, 26) != 1:
raise ValueError(f"Invalid Matrix: Determinant {det} is not coprime to 26.")
self.det_inv = mod_inv(det, 26)
# Adjugate matrix: [k22, -k12; -k21, k11]
self.inv11 = (self.k22 * self.det_inv) % 26
self.inv12 = (-self.k12 * self.det_inv) % 26
self.inv21 = (-self.k21 * self.det_inv) % 26
self.inv22 = (self.k11 * self.det_inv) % 26
def encrypt(self, plaintext: str) -> str:
clean = [ord(c) - ord('A') for c in plaintext.upper() if c.isalpha()]
if len(clean) % 2 != 0:
clean.append(ord('X') - ord('A')) # Pad with 'X'
cipher_chars = []
for i in range(0, len(clean), 2):
p1, p2 = clean[i], clean[i + 1]
c1 = (self.k11 * p1 + self.k12 * p2) % 26
c2 = (self.k21 * p1 + self.k22 * p2) % 26
cipher_chars.extend([chr(c1 + ord('A')), chr(c2 + ord('A'))])
return "".join(cipher_chars)
def decrypt(self, ciphertext: str) -> str:
clean = [ord(c) - ord('A') for c in ciphertext.upper() if c.isalpha()]
plain_chars = []
for i in range(0, len(clean), 2):
c1, c2 = clean[i], clean[i + 1]
p1 = (self.inv11 * c1 + self.inv12 * c2) % 26
p2 = (self.inv21 * c1 + self.inv22 * c2) % 26
plain_chars.extend([chr(p1 + ord('A')), chr(p2 + ord('A'))])
return "".join(plain_chars)
if __name__ == "__main__":
# Key Matrix K = [[3, 3], [2, 5]] -> det(K) = 15 - 6 = 9. gcd(9, 26) = 1.
hill = HillCipher2x2(3, 3, 2, 5)
msg = "HELP"
cipher_text = hill.encrypt(msg)
recovered_text = hill.decrypt(cipher_text)
print(f"[*] Plaintext : {msg}")
print(f"[*] Encryption Matrix: [[3, 3], [2, 5]]")
print(f"[+] Hill Ciphertext : {cipher_text}")
print(f"[β] Recovered Text : {recovered_text}")
assert recovered_text == msg
class VigenereCipher:
"""
Encryption: C_i = (P_i + K_(i mod m)) mod 26
Decryption: P_i = (C_i - K_(i mod m) + 26) mod 26
where m is the length of key string K.
"""
def __init__(self, key: str):
self.key = [ord(c) - ord('A') for c in key.upper() if c.isalpha()]
if not self.key:
raise ValueError("Key must contain at least one alphabetic character.")
def encrypt(self, plaintext: str) -> str:
result = []
k_idx = 0
for char in plaintext.upper():
if char.isalpha():
p = ord(char) - ord('A')
k = self.key[k_idx % len(self.key)]
c = (p + k) % 26
result.append(chr(c + ord('A')))
k_idx += 1
else:
result.append(char)
return "".join(result)
def decrypt(self, ciphertext: str) -> str:
result = []
k_idx = 0
for char in ciphertext.upper():
if char.isalpha():
c = ord(char) - ord('A')
k = self.key[k_idx % len(self.key)]
p = (c - k + 26) % 26
result.append(chr(p + ord('A')))
k_idx += 1
else:
result.append(char)
return "".join(result)
if __name__ == "__main__":
vigenere = VigenereCipher("LEMON")
text = "ATTACKATDAWN"
cipher = vigenere.encrypt(text)
decrypted = vigenere.decrypt(cipher)
print(f"[*] Plaintext : {text}")
print(f"[*] Key : LEMON (Period m=5)")
print(f"[+] Vigenère Cipher : {cipher}")
print(f"[β] Recovered Text : {decrypted}")
assert decrypted == text
import math
class ColumnarTranspositionCipher:
def __init__(self, key: str):
self.key = key.upper()
# Derive permutation order based on alphabetical sorting of key characters
self.col_order = sorted(range(len(self.key)), key=lambda k: self.key[k])
def encrypt(self, plaintext: str) -> str:
clean = [c for c in plaintext.upper() if c.isalpha()]
num_cols = len(self.key)
num_rows = math.ceil(len(clean) / num_cols)
# Pad with 'X' to complete rectangular grid
padded_len = num_rows * num_cols
clean += ['X'] * (padded_len - len(clean))
# Build grid
grid = [clean[i * num_cols:(i + 1) * num_cols] for i in range(num_rows)]
# Read columns off in alphabetical key order
ciphertext = []
for col_idx in self.col_order:
for row in range(num_rows):
ciphertext.append(grid[row][col_idx])
return "".join(ciphertext)
def decrypt(self, ciphertext: str) -> str:
num_cols = len(self.key)
num_rows = len(ciphertext) // num_cols
# Allocate empty grid
grid = [[''] * num_cols for _ in range(num_rows)]
# Populate columns in permutation order
curr_idx = 0
for col_idx in self.col_order:
for row in range(num_rows):
grid[row][col_idx] = ciphertext[curr_idx]
curr_idx += 1
# Read row-by-row
plaintext = []
for r in range(num_rows):
plaintext.extend(grid[r])
return "".join(plaintext)
if __name__ == "__main__":
transposition = ColumnarTranspositionCipher("ZEBRAS")
message = "DEFENDTHEEASTWALL"
encrypted_msg = transposition.encrypt(message)
decrypted_msg = transposition.decrypt(encrypted_msg)
print(f"[*] Plaintext : {message}")
print(f"[*] Key : ZEBRAS -> Col Order: {transposition.col_order}")
print(f"[+] Transposed Cipher: {encrypted_msg}")
print(f"[β] Recovered Text : {decrypted_msg}")
from collections import Counter
# Standard English letter frequencies (Percentages normalized to sum to 1.0)
ENGLISH_FREQS = {
'E': 0.1202, 'T': 0.0910, 'A': 0.0812, 'O': 0.0768, 'I': 0.0731,
'N': 0.0695, 'S': 0.0628, 'R': 0.0602, 'H': 0.0592, 'D': 0.0432,
'L': 0.0398, 'U': 0.0288, 'C': 0.0271, 'M': 0.0261, 'F': 0.0230,
'Y': 0.0211, 'W': 0.0209, 'G': 0.0203, 'P': 0.0182, 'B': 0.0149,
'V': 0.0111, 'K': 0.0069, 'X': 0.0017, 'Q': 0.0011, 'J': 0.0010,
'Z': 0.0007
}
def chi_squared_score(text: str) -> float:
"""Calculates Chi-Squared statistic against English frequency distribution."""
n = len(text)
if n == 0:
return float('inf')
counts = Counter(text)
chi_sq = 0.0
for char, expected_freq in ENGLISH_FREQS.items():
observed = counts.get(char, 0)
expected = n * expected_freq
chi_sq += ((observed - expected) ** 2) / expected
return chi_sq
def break_caesar(ciphertext: str) -> tuple:
clean = [c for c in ciphertext.upper() if c.isalpha()]
best_shift = 0
lowest_chi = float('inf')
best_plaintext = ""
for shift in range(26):
candidate = []
for c in clean:
decrypted_char = chr(((ord(c) - ord('A') - shift) % 26) + ord('A'))
candidate.append(decrypted_char)
cand_str = "".join(candidate)
score = chi_squared_score(cand_str)
if score < lowest_chi:
lowest_chi = score
best_shift = shift
best_plaintext = cand_str
return best_shift, lowest_chi, best_plaintext
if __name__ == "__main__":
secret_message = "CRYPTOGRAPHYISESSENTIALFORSECURINGDISTRIBUTEDSYSTEMSAGAINSTADVERSARIES"
# Encrypt with Caesar Shift = 13 (ROT13)
caesar_encrypted = "".join([chr(((ord(c) - ord('A') + 13) % 26) + ord('A')) for c in secret_message])
print(f"[+] Intercepted Ciphertext: {caesar_encrypted}")
recovered_shift, score, decrypted_text = break_caesar(caesar_encrypted)
print(f"[*] Cryptanalysis Result : Recovered Shift Key = {recovered_shift} (Chi-Square: {score:.2f})")
print(f"[β] Decrypted Plaintext : {decrypted_text}")
from collections import Counter
def calculate_ioc(text: str) -> float:
"""
Computes the Index of Coincidence:
IoC = sum(f_i * (f_i - 1)) / (N * (N - 1))
Natural English text: IoC ~= 0.0667
Uniform random distribution: IoC ~= 0.0385 (1/26)
"""
clean = [c for c in text.upper() if c.isalpha()]
n = len(clean)
if n <= 1:
return 0.0
counts = Counter(clean)
numerator = sum(f * (f - 1) for f in counts.values())
denominator = n * (n - 1)
return numerator / denominator
def estimate_vigenere_key_length(ciphertext: str, max_period: int = 10) -> int:
clean = [c for c in ciphertext.upper() if c.isalpha()]
best_key_len = 1
best_ioc_avg = 0.0
print(f"{'PERIOD (m)':<12} | {'AVERAGE IoC':<12} | {'LIKELIHOOD'}")
print("-" * 45)
for period in range(1, max_period + 1):
# Partition ciphertext into m independent streams
slices = [clean[i::period] for i in range(period)]
avg_ioc = sum(calculate_ioc("".join(s)) for s in slices) / period
# Check proximity to natural English IoC (~0.067)
likelihood = "HIGH (English Match)" if avg_ioc >= 0.060 else "LOW (Random Spread)"
print(f"{period:<12} | {avg_ioc:<12.4f} | {likelihood}")
if avg_ioc > best_ioc_avg:
best_ioc_avg = avg_ioc
best_key_len = period
return best_key_len
if __name__ == "__main__":
# Vigenère ciphertext encrypted with key "CIPHER" (length m=6)
vigenere_sample = (
"KPVSVMTKNLCHGXZKPTCWXMVLMCYPTCWXMNWOPVSVMTKNLCHGXZKPTCWXMVLMCY"
"PTCWXMNWOPVSVMTKNLCHGXZKPTCWXMVLMCYPTCWXMNWOPVSVMTKNLCHGXZKPTCW"
)
detected_period = estimate_vigenere_key_length(vigenere_sample, max_period=8)
print(f"\n[β] Cryptanalytic Finding: Detected Key Length m = {detected_period}")
CLASSICAL CRYPTOGRAPHIC DEFECTS & MATHEMATICAL REMEDIATION:
// ==============================================================================
// PITFALL 1: PYTHON VS C/JAVA NEGATIVE MODULO OPERATOR BEHAVIOR
// DEFECT: In C/C++/Java, (-5 % 26) evaluates to -5!
// In Python, (-5 % 26) evaluates correctly to 21.
// PROBLEM: Decryption formulas like P = (C - K) % 26 produce negative indices in C/Java!
// FIX: Always normalize using: P = ((C - K) % 26 + 26) % 26
// ==============================================================================
// ==============================================================================
// PITFALL 2: CHOOSING A NON-INVERTIBLE AFFINE OR HILL CIPHER KEY
// DEFECT: Selecting Affine key a=13, or Hill matrix with det(K) = 13.
// ERROR: gcd(13, 26) = 13 != 1.
// CONSEQUENCE: The encryption function is not a bijection (not one-to-one). Multiple
// distinct plaintext letters produce the same ciphertext letter!
// RESULT: Decryption is mathematically impossible due to missing modular inverse.
// FIX: Enforce validation: assert math.gcd(det, 26) == 1 during key generation!
// ==============================================================================
// ==============================================================================
// PITFALL 3: PLAYFAIR CIPHER IDENTICAL LETTER DIGRAPH COLLISION
// DEFECT: Attempting to encrypt "BALLOON" directly as ("BA", "LL", "OO", "N").
// ERROR: Playfair rules cannot evaluate identical letter pairs like "LL" in the matrix!
// FIX: Insert filler character 'X' on repeated letters: ("BA", "LX", "LO", "ON").
// ==============================================================================
CLASSICAL CIPHERS & CRYPTANALYSIS SPECIFICATION MATRIX:
βββββββββββββββββββββββββββ¬βββββββββββββββββββββββββββββββ¬βββββββββββββββββββ¬ββββββββββββββββββββββββββββββββ
β CIPHER SYSTEM β MATHEMATICAL FORMULA β KEY SPACE SIZE β PRIMARY CRYPTANALYTIC ATTACK β
βββββββββββββββββββββββββββΌβββββββββββββββββββββββββββββββΌβββββββββββββββββββΌββββββββββββββββββββββββββββββββ€
β Caesar (Shift) Cipher β C = (P + k) mod 26 β 26 (25 non-zero) β Brute Force (Exhaustive searchβ
β β β β or Chi-Squared frequency) β
βββββββββββββββββββββββββββΌβββββββββββββββββββββββββββββββΌβββββββββββββββββββΌββββββββββββββββββββββββββββββββ€
β Affine Cipher β C = (a*P + b) mod 26 β 12 * 26 = 312 β Frequency Analysis on high- β
β β a in {coprimes}, b in [0..25]β β frequency letters ('E', 'T') β
βββββββββββββββββββββββββββΌβββββββββββββββββββββββββββββββΌβββββββββββββββββββΌββββββββββββββββββββββββββββββββ€
β Playfair Cipher β 5x5 Matrix Digraph Rules β 25! ~= 1.55 x 10^25β Digraph frequency analysis β
β β Rectangle, Row, Column β β & known-plaintext pairs β
βββββββββββββββββββββββββββΌβββββββββββββββββββββββββββββββΌβββββββββββββββββββΌββββββββββββββββββββββββββββββββ€
β Hill Cipher (nxn) β C = K * P mod 26 β Limited by β Known-Plaintext Attack: Solve β
β β gcd(det(K), 26) == 1 β invertible gl(n) β P * K = C via matrix inversionβ
βββββββββββββββββββββββββββΌβββββββββββββββββββββββββββββββΌβββββββββββββββββββΌββββββββββββββββββββββββββββββββ€
β VigenΓ¨re Cipher β C_i = (P_i + K_i) mod 26 β 26^m (m=key len) β Kasiski Examination / Index β
β β Polyalphabetic Periodic β β of Coincidence (IoC ~= 0.067) β
βββββββββββββββββββββββββββΌβββββββββββββββββββββββββββββββΌβββββββββββββββββββΌββββββββββββββββββββββββββββββββ€
β Columnar Transposition β Permutation grid reading β m! (m=columns) β Bigram/trigram anagramming & β
β β Positions permuted β β multiple anagramming analysis β
βββββββββββββββββββββββββββΌβββββββββββββββββββββββββββββββΌβββββββββββββββββββΌββββββββββββββββββββββββββββββββ€
β One-Time Pad (Vernam) β C = P XOR K (Random key) β 2^(text length) β Perfect Secrecy (Shannon): β
β β Key length == Message length β Infinite entropy β Mathematically unbreakable β
βββββββββββββββββββββββββββ΄βββββββββββββββββββββββββββββββ΄βββββββββββββββββββ΄ββββββββββββββββββββββββββββββββ€
β TOP 5 CLASSICAL CRYPTOGRAPHIC AXIOMS: β
β 1. Monoalphabetic substitution never hides letter frequency: Frequencies map directly to ciphertext. β
β 2. Coprimality is mandatory for modular decryption: gcd(a, m) = 1 is required for a modular inverse. β
β 3. Polyalphabetic ciphers periodic keys leak via IoC: Dividing ciphertext by period reveals patterns. β
β 4. Transposition preserves character frequencies: Analyzed using vowel-consonant position patterns. β
β 5. Perfect Secrecy requires an unshared, purely random key used once: The One-Time Pad (Vernam). β
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ