CTF Learning
Kembali

Cryptography

Teknik pemecahan kode rahasia dan enkripsi data

Essential Tools

CyberChefdcode.frRsaCtfToolJohn the Ripperhashcatfactordb.com

Caesar Cipher

Mudah

Cipher klasik yang menggeser huruf dengan jumlah tertentu dalam alfabet.

Cara Kerjatext
1Plaintext: HELLO WORLD
2Shift: 3
3
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 Z
5↓ ↓ ↓ ↓ ↓ ↓ ↓ ↓ ↓ ↓ ↓ ↓ ↓ ↓ ↓ ↓ ↓ ↓ ↓ ↓ ↓ ↓ ↓ ↓ ↓ ↓
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 C
7
8Ciphertext: KHOOR ZRUOG
9
10CTF Tip: ROT13 adalah Caesar dengan shift=13 (self-inverse)

Demo Interaktif

Caesar Cipher Tool

Encrypt/decrypt pesan atau bruteforce semua rotasi

3

Hasil:

-

Vigenère Cipher

Menengah

Cipher polyalphabetic yang menggunakan keyword untuk enkripsi.

Cara Kerja Vigenèretext
1Plaintext: ATTACKATDAWN
2Keyword: 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: LXFOPVEFRNHR
Breaking Vigenèretext
11. Kasiski Examination - Cari repeated sequences
2 LXFOPV...LXFOPV (jarak 12)
3 Key length kemungkinan: 2, 3, 4, 6, 12
4
52. Index of Coincidence
6 - Bahasa Inggris IC ≈ 0.067
7 - Random text IC ≈ 0.038
8 - Hitung IC untuk tiap key length, pilih yang mendekati 0.067
9
103. Frequency Analysis per grup
11 - Bagi ciphertext berdasarkan key length
12 - Tiap grup = Caesar cipher
13 - Crack dengan frequency analysis
14
15Tools: dcode.fr, CyberChef, online Vigenère solver
Python Bruteforce Scriptpython
1from itertools import product
2import string
3
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 attack
15ct = "LXFOPVEFRNHR"
16known = "ATTACK" # We suspect this is the start
17
18# Recover partial key
19for 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 keys
24for 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

Mudah

Operasi bitwise XOR untuk enkripsi. Sangat umum di CTF!

XOR Properties (WAJIB HAFAL)text
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)

XOR Attack Scriptspython
1# Single-byte XOR bruteforce
2def 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 pass
11
12ciphertext = bytes.fromhex("1b37373331363f78151b7f2b783431333d")
13single_byte_xor(ciphertext)
14
15# Multi-byte XOR with known plaintext
16def 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_part
20
21ct = bytes.fromhex("...")
22known = b"FLAG{" # CTF flags often start with this
23key_start = recover_key(ct, known)
24print(f"Key starts with: {key_start}")
25
26# Repeating-key XOR decrypt
27def 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 distance
31def 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 continue
40 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

Sulit

Asymmetric encryption yang paling sering muncul di CTF crypto.

RSA Fundamentalstext
1KEY GENERATION:
21. Choose 2 large primes: p, q
32. n = p × q
43. φ(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 n
12DECRYPTION: m = c^d mod n
13
14Yang perlu dicari di CTF:
15- n, e, c biasanya diberikan
16- Tujuan: cari d atau langsung decrypt m

Common 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

RSA Attack Scriptspython
1from Crypto.Util.number import long_to_bytes, inverse, GCD
2import gmpy2
3
4# Given values
5n = 123456789...
6e = 65537
7c = 987654321...
8
9# ========== Attack 1: Factor n (use factordb.com) ==========
10p = 123... # dari factordb
11q = n // p
12phi = (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 = 3
20m, 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 owiener
26import owiener
27d = 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) = 1
35def 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 = -a
40 if b < 0:
41 c2 = inverse(c2, n)
42 b = -b
43 m = (pow(c1, a, n) * pow(c2, b, n)) % n
44 return m
45
46# ========== Attack 5: Fermat Factorization ==========
47def fermat_factor(n):
48 a = gmpy2.isqrt(n) + 1
49 b2 = a * a - n
50 while not gmpy2.is_square(b2):
51 a += 1
52 b2 = a * a - n
53 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

Sulit

Symmetric encryption dan attack pada implementasi yang lemah.

Block Cipher Modestext
1ECB (Electronic Codebook) - VULNERABLE!
2- Same plaintext block → same ciphertext block
3- Pattern leakage, block manipulation possible
4- Attack: Cut and paste blocks
5
6CBC (Cipher Block Chaining)
7- XOR dengan block sebelumnya
8- IV (Initialization Vector) penting
9- Attack: Padding Oracle, Bit Flipping
10
11CTR (Counter Mode)
12- Essentially stream cipher
13- Key + nonce + counter
14- Attack: Nonce reuse = XOR attack
15
16GCM (Galois/Counter Mode)
17- CTR + authentication
18- Nonce reuse very dangerous
ECB Block Attackpython
1# ECB mode: same plaintext block = same ciphertext block
2# Dapat digunakan untuk byte-by-byte bruteforce
3
4def ecb_oracle(data):
5 """Oracle yang encrypt data dengan ECB mode"""
6 # Tambahkan secret di belakang
7 plaintext = data + SECRET
8 return AES_ECB_encrypt(plaintext, KEY)
9
10def ecb_byte_by_byte():
11 block_size = 16
12 known = b""
13
14 for i in range(len_secret):
15 # Padding sehingga byte yang mau ditebak ada di akhir block
16 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 tersebut
20 for byte in range(256):
21 test = padding + known + bytes([byte])
22 if ecb_oracle(test)[:len(target)] == target:
23 known += bytes([byte])
24 break
25
26 return known
CBC Bit Flipping Attackpython
1# CBC: flip bit di ciphertext block N → flip bit di plaintext block N+1
2# Berguna untuk mengubah plaintext tanpa tahu key
3
4# Contoh: mengubah ";admin=0" menjadi ";admin=1"
5# Target byte di posisi tertentu
6
7def cbc_bitflip(ciphertext, block_with_target, byte_position, original_byte, target_byte):
8 """
9 Flip byte di block sebelum target untuk mengubah plaintext
10 """
11 iv_block = block_with_target - 1 # Block yang akan dimodifikasi
12
13 # XOR untuk mengubah original_byte menjadi target_byte
14 flip = original_byte ^ target_byte
15
16 # Modify ciphertext
17 ct = bytearray(ciphertext)
18 ct[iv_block * 16 + byte_position] ^= flip
19
20 return bytes(ct)
21
22# Padding Oracle Attack - lebih kompleks
23# Tool: PadBuster, atau implement sendiri
24# Konsep: exploit error message untuk decrypt byte-by-byte

Encoding Reference

Mudah

Bukan enkripsi! Hanya encoding. Mudah di-decode.

Common Encodings di CTFtext
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 encoding
14- Multiple layers? Decode berulang
15- Lihat pattern untuk identify encoding

Demo Interaktif

Base64 Encoder/Decoder

Tool untuk encode/decode Base64

Hash Cracking

Menengah

Menemukan plaintext dari hash yang diberikan.

Hash Identificationtext
1MD5: 32 hex chars 5d41402abc4b2a76b9719d911017c592
2SHA1: 40 hex chars aaf4c61ddcc5e8a2dabede0f3b482cd9aea9434d
3SHA256: 64 hex chars 2cf24dba5fb0a30e26e83b2ac5b9e29e1b161e5c...
4SHA512: 128 hex chars 9b71d224bd62f3785d96d46ad3ea3d73319bfbc...
5bcrypt: $2a$/$2b$/$2y$ $2a$10$N9qo8uLOickgx2ZMRZoMy...
6MD5crypt: $1$ $1$salt$...
7
8Tool: hash-identifier, hashid
9Online: hashes.org, crackstation.net
Hash Cracking Toolsbash
1# John the Ripper
2john --format=raw-md5 --wordlist=rockyou.txt hash.txt
3john --format=raw-sha256 hash.txt
4john --show hash.txt
5
6# Hashcat (faster with GPU)
7# MD5=0, SHA1=100, SHA256=1400, bcrypt=3200
8hashcat -m 0 hash.txt rockyou.txt
9hashcat -m 0 hash.txt -a 3 ?a?a?a?a?a # bruteforce 5 chars
10
11# Custom rules for variations
12hashcat -m 0 hash.txt rockyou.txt -r rules/best64.rule
13
14# Online crackers
15# crackstation.net (rainbow tables)
16# hashes.com
17# md5decrypt.net