Cryptography
Teknik pemecahan kode rahasia dan enkripsi data
Essential Tools
Caesar Cipher
MudahCipher klasik yang menggeser huruf dengan jumlah tertentu dalam alfabet.
1Plaintext: HELLO WORLD2Shift: 33 4A B C D E F G H I J K L M N O P Q R S T U V W X Y Z5↓ ↓ ↓ ↓ ↓ ↓ ↓ ↓ ↓ ↓ ↓ ↓ ↓ ↓ ↓ ↓ ↓ ↓ ↓ ↓ ↓ ↓ ↓ ↓ ↓ ↓6D E F G H I J K L M N O P Q R S T U V W X Y Z A B C7 8Ciphertext: KHOOR ZRUOG9 10CTF Tip: ROT13 adalah Caesar dengan shift=13 (self-inverse)Demo Interaktif
Caesar Cipher Tool
Encrypt/decrypt pesan atau bruteforce semua rotasi
Hasil:
-
Vigenère Cipher
MenengahCipher polyalphabetic yang menggunakan keyword untuk enkripsi.
1Plaintext: ATTACKATDAWN2Keyword: LEMONLEMONLE (repeated)3 4A + L = L (0 + 11 = 11)5T + E = X (19 + 4 = 23)6T + M = F (19 + 12 = 31 mod 26 = 5)7...8 9Ciphertext: LXFOPVEFRNHR11. Kasiski Examination - Cari repeated sequences2 LXFOPV...LXFOPV (jarak 12)3 Key length kemungkinan: 2, 3, 4, 6, 124 52. Index of Coincidence6 - Bahasa Inggris IC ≈ 0.0677 - Random text IC ≈ 0.0388 - Hitung IC untuk tiap key length, pilih yang mendekati 0.0679 103. Frequency Analysis per grup11 - Bagi ciphertext berdasarkan key length12 - Tiap grup = Caesar cipher13 - Crack dengan frequency analysis14 15Tools: dcode.fr, CyberChef, online Vigenère solver1from itertools import product2import string3 4def vigenere_decrypt(ct, key):5 result = []6 for i, c in enumerate(ct.upper()):7 if c in string.ascii_uppercase:8 shift = ord(key[i % len(key)].upper()) - ord('A')9 result.append(chr((ord(c) - ord('A') - shift) % 26 + ord('A')))10 else:11 result.append(c)12 return ''.join(result)13 14# Known plaintext attack15ct = "LXFOPVEFRNHR"16known = "ATTACK" # We suspect this is the start17 18# Recover partial key19for i in range(len(known)):20 key_char = chr((ord(ct[i]) - ord(known[i])) % 26 + ord('A'))21 print(f"Position {i}: {key_char}")22 23# Bruteforce short keys24for length in range(3, 8):25 for key in product(string.ascii_uppercase, repeat=length):26 key = ''.join(key)27 result = vigenere_decrypt(ct, key)28 if 'FLAG' in result or 'CTF' in result:29 print(f"Key: {key}, Result: {result}")XOR Cipher
MudahOperasi bitwise XOR untuk enkripsi. Sangat umum di CTF!
1A ⊕ 0 = A (XOR dengan 0 = tidak berubah)2A ⊕ A = 0 (XOR dengan diri sendiri = 0)3A ⊕ B = B ⊕ A (commutative)4(A ⊕ B) ⊕ C = A ⊕ (B ⊕ C) (associative)5 6PENTING:7Jika: C = P ⊕ K (Ciphertext = Plaintext XOR Key)8Maka: P = C ⊕ K (untuk decrypt, XOR lagi dengan key)9Dan: K = C ⊕ P (jika tau plaintext, bisa recover key!)10 11Ini artinya: Known Plaintext Attack sangat efektif!Demo Interaktif
XOR Tool
XOR data dengan key (supports text dan hex input)
1# Single-byte XOR bruteforce2def single_byte_xor(data):3 for key in range(256):4 result = bytes([b ^ key for b in data])5 try:6 decoded = result.decode('ascii')7 if decoded.isprintable() and 'flag' in decoded.lower():8 print(f"Key {key} ({chr(key) if 32<=key<127 else 'unprintable'}): {decoded}")9 except:10 pass11 12ciphertext = bytes.fromhex("1b37373331363f78151b7f2b783431333d")13single_byte_xor(ciphertext)14 15# Multi-byte XOR with known plaintext16def recover_key(ciphertext, known_plaintext):17 """If we know part of the plaintext, recover that part of the key"""18 key_part = bytes([c ^ p for c, p in zip(ciphertext, known_plaintext)])19 return key_part20 21ct = bytes.fromhex("...")22known = b"FLAG{" # CTF flags often start with this23key_start = recover_key(ct, known)24print(f"Key starts with: {key_start}")25 26# Repeating-key XOR decrypt27def repeating_key_xor(data, key):28 return bytes([data[i] ^ key[i % len(key)] for i in range(len(data))])29 30# Find XOR key length using Hamming distance31def hamming_distance(b1, b2):32 return sum(bin(a ^ b).count('1') for a, b in zip(b1, b2))33 34def find_keysize(data, max_keysize=40):35 scores = []36 for keysize in range(2, max_keysize):37 chunks = [data[i:i+keysize] for i in range(0, len(data), keysize)][:4]38 if len(chunks) < 2:39 continue40 distances = [hamming_distance(chunks[i], chunks[j]) / keysize 41 for i in range(len(chunks)) for j in range(i+1, len(chunks))]42 scores.append((keysize, sum(distances) / len(distances)))43 return sorted(scores, key=lambda x: x[1])[:5]RSA - Complete Attack Guide
SulitAsymmetric encryption yang paling sering muncul di CTF crypto.
1KEY GENERATION:21. Choose 2 large primes: p, q32. n = p × q43. φ(n) = (p-1)(q-1) [Euler's totient]54. Choose e where gcd(e, φ(n)) = 1 [usually 65537]65. d = e⁻¹ mod φ(n) [modular inverse]7 8Public Key: (n, e)9Private Key: (n, d) [atau p, q, d]10 11ENCRYPTION: c = m^e mod n12DECRYPTION: m = c^d mod n13 14Yang perlu dicari di CTF:15- n, e, c biasanya diberikan16- Tujuan: cari d atau langsung decrypt mCommon RSA Attacks:
1. Small n - Factor n
factordb.com atau factor sendiri
2. Small e (e=3)
Cube root langsung tanpa mod
3. Wiener Attack
d kecil → continued fractions
4. Common Modulus
n sama, e berbeda → recover m
5. Fermat Factorization
p dan q terlalu dekat
6. Hastad Attack
Same m, different n, small e
1from Crypto.Util.number import long_to_bytes, inverse, GCD2import gmpy23 4# Given values5n = 123456789...6e = 655377c = 987654321...8 9# ========== Attack 1: Factor n (use factordb.com) ==========10p = 123... # dari factordb11q = n // p12phi = (p - 1) * (q - 1)13d = inverse(e, phi)14m = pow(c, d, n)15print(long_to_bytes(m))16 17# ========== Attack 2: Small e (cube root) ==========18# Jika e=3 dan m kecil, c = m^3 (tanpa mod)19e = 320m, is_perfect = gmpy2.iroot(c, e)21if is_perfect:22 print(long_to_bytes(m))23 24# ========== Attack 3: Wiener (d kecil) ==========25# pip install owiener26import owiener27d = owiener.attack(e, n)28if d:29 m = pow(c, d, n)30 print(long_to_bytes(m))31 32# ========== Attack 4: Common Modulus ==========33# Same n, two different (e1, c1) and (e2, c2)34# Syarat: gcd(e1, e2) = 135def common_modulus_attack(n, e1, c1, e2, c2):36 g, a, b = gmpy2.gcdext(e1, e2)37 if a < 0:38 c1 = inverse(c1, n)39 a = -a40 if b < 0:41 c2 = inverse(c2, n)42 b = -b43 m = (pow(c1, a, n) * pow(c2, b, n)) % n44 return m45 46# ========== Attack 5: Fermat Factorization ==========47def fermat_factor(n):48 a = gmpy2.isqrt(n) + 149 b2 = a * a - n50 while not gmpy2.is_square(b2):51 a += 152 b2 = a * a - n53 b = gmpy2.isqrt(b2)54 return int(a - b), int(a + b)55 56# ========== RsaCtfTool (automatic) ==========57# python RsaCtfTool.py -n <n> -e <e> --uncipher <c>AES & Block Cipher Attacks
SulitSymmetric encryption dan attack pada implementasi yang lemah.
1ECB (Electronic Codebook) - VULNERABLE!2- Same plaintext block → same ciphertext block3- Pattern leakage, block manipulation possible4- Attack: Cut and paste blocks5 6CBC (Cipher Block Chaining)7- XOR dengan block sebelumnya8- IV (Initialization Vector) penting9- Attack: Padding Oracle, Bit Flipping10 11CTR (Counter Mode)12- Essentially stream cipher13- Key + nonce + counter14- Attack: Nonce reuse = XOR attack15 16GCM (Galois/Counter Mode)17- CTR + authentication18- Nonce reuse very dangerous1# ECB mode: same plaintext block = same ciphertext block2# Dapat digunakan untuk byte-by-byte bruteforce3 4def ecb_oracle(data):5 """Oracle yang encrypt data dengan ECB mode"""6 # Tambahkan secret di belakang7 plaintext = data + SECRET8 return AES_ECB_encrypt(plaintext, KEY)9 10def ecb_byte_by_byte():11 block_size = 1612 known = b""13 14 for i in range(len_secret):15 # Padding sehingga byte yang mau ditebak ada di akhir block16 padding = b"A" * (block_size - 1 - (len(known) % block_size))17 target = ecb_oracle(padding)[:block_size * ((len(known) // block_size) + 1)]18 19 # Bruteforce byte tersebut20 for byte in range(256):21 test = padding + known + bytes([byte])22 if ecb_oracle(test)[:len(target)] == target:23 known += bytes([byte])24 break25 26 return known1# CBC: flip bit di ciphertext block N → flip bit di plaintext block N+12# Berguna untuk mengubah plaintext tanpa tahu key3 4# Contoh: mengubah ";admin=0" menjadi ";admin=1"5# Target byte di posisi tertentu6 7def cbc_bitflip(ciphertext, block_with_target, byte_position, original_byte, target_byte):8 """9 Flip byte di block sebelum target untuk mengubah plaintext10 """11 iv_block = block_with_target - 1 # Block yang akan dimodifikasi12 13 # XOR untuk mengubah original_byte menjadi target_byte14 flip = original_byte ^ target_byte15 16 # Modify ciphertext17 ct = bytearray(ciphertext)18 ct[iv_block * 16 + byte_position] ^= flip19 20 return bytes(ct)21 22# Padding Oracle Attack - lebih kompleks23# Tool: PadBuster, atau implement sendiri24# Konsep: exploit error message untuk decrypt byte-by-byteEncoding Reference
MudahBukan enkripsi! Hanya encoding. Mudah di-decode.
1Base64: A-Za-z0-9+/= (padding: =)2Base32: A-Z2-7= (padding: =, all caps)3Base58: 1-9A-HJ-NP-Za-km-z (no 0, O, l, I)4Hex: 0-9a-f (2 chars per byte)5Binary: 0/1 (8 bits per byte)6Octal: 0-7 (3 digits per byte)7URL: %XX (hex value)8HTML: &#XX; atau &#xXX; (decimal atau hex)9ROT13: Self-inverse Caesar (shift 13)10Morse: .-/ (dots, dashes, spaces)11 12TIPS:13- CyberChef "Magic" mode = auto detect encoding14- Multiple layers? Decode berulang15- Lihat pattern untuk identify encodingDemo Interaktif
Base64 Encoder/Decoder
Tool untuk encode/decode Base64
Hash Cracking
MenengahMenemukan plaintext dari hash yang diberikan.
1MD5: 32 hex chars 5d41402abc4b2a76b9719d911017c5922SHA1: 40 hex chars aaf4c61ddcc5e8a2dabede0f3b482cd9aea9434d3SHA256: 64 hex chars 2cf24dba5fb0a30e26e83b2ac5b9e29e1b161e5c...4SHA512: 128 hex chars 9b71d224bd62f3785d96d46ad3ea3d73319bfbc...5bcrypt: $2a$/$2b$/$2y$ $2a$10$N9qo8uLOickgx2ZMRZoMy...6MD5crypt: $1$ $1$salt$...7 8Tool: hash-identifier, hashid9Online: hashes.org, crackstation.net1# John the Ripper2john --format=raw-md5 --wordlist=rockyou.txt hash.txt3john --format=raw-sha256 hash.txt4john --show hash.txt5 6# Hashcat (faster with GPU)7# MD5=0, SHA1=100, SHA256=1400, bcrypt=32008hashcat -m 0 hash.txt rockyou.txt9hashcat -m 0 hash.txt -a 3 ?a?a?a?a?a # bruteforce 5 chars10 11# Custom rules for variations12hashcat -m 0 hash.txt rockyou.txt -r rules/best64.rule13 14# Online crackers15# crackstation.net (rainbow tables)16# hashes.com17# md5decrypt.net