Lab 2: Substitution Cipher - Memecahkan dengan Frekuensi Huruf
Target: Memahami cipher substitusi monoalfabetik dan frequency analysis
Tools:python3
Konsep
Substitution cipher mengganti setiap huruf dengan huruf lain secara acak (tidak sekedar shift). Ada 26! (~4×10²⁶) kemungkinan - terlalu banyak untuk brute force.
Tapi bisa dipecahkan dengan frequency analysis: huruf yang paling sering muncul dalam ciphertext kemungkinan besar adalah 'E' (huruf paling umum dalam bahasa Inggris).
Praktikum
cd ~ && mkdir crypto-lab2 && cd crypto-lab2
python3 << 'PYEOF'
import string, random
from collections import Counter
# Buat substitusi acak
alphabet = list(string.ascii_uppercase)
shuffled = alphabet.copy()
random.seed(42) # reproducible
random.shuffle(shuffled)
subst = dict(zip(alphabet, shuffled))
reverse = {v: k for k, v in subst.items()}
def encrypt(text):
return ''.join(subst.get(c, c) for c in text.upper())
def decrypt(text, mapping):
return ''.join(mapping.get(c, c) for c in text)
# Sample text
plaintext = "THE QUICK BROWN FOX JUMPS OVER THE LAZY DOG THIS IS A SECRET MESSAGE"
ciphertext = encrypt(plaintext)
print(f"Plain: {plaintext}")
print(f"Cipher: {ciphertext}")
print()
# Frequency analysis
freq = Counter(c for c in ciphertext if c in string.ascii_uppercase)
print("=== Frekuensi Huruf (sorted) ===")
for char, count in freq.most_common():
print(f" {char}: {count}")
print()
# Bahasa Inggris: E > T > A > O > I > N > S > H > R > D > L > C > U > M
# Tebak: huruf paling sering = E
english_freq = 'ETAOINSHRDLCUMWFGYPBVKJXQZ'
cipher_freq = ''.join(freq.keys())
# Buat mapping tebakan
guess = {}
for i, c in enumerate(cipher_freq):
if i < len(english_freq):
guess[c] = english_freq[i]
print("=== Tebakan Awal (E=T, T=A, etc) ===")
partial = decrypt(ciphertext, guess)
print(partial)
print("\n(Catatan: perlu penyesuaian manual untuk hasil sempurna)")
PYEOF
️ Analisis
| Teknik | Cara Kerja |
|---|---|
| Frequency Analysis | Hitung frekuensi huruf → cocokkan dengan distribusi bahasa |
| Pattern Matching | Kata pendek (THE, AND, THAT) mudah dikenali |
| Dictionary | Cocokkan dengan kata dalam kamus |
Refleksi: Substitution cipher aman dari brute force (26! key) tapi rentan terhadap frequency analysis. Inilah awal mula kriptanalisis - ilmu memecahkan cipher tanpa kunci.
Generated by @farishhz Agent Pentest Pipeline - TDCTF Security Academy