The training method behind a top Chinese CTF team: Part 4 cryptography
This is Part 4 of my walk through "Handbook for CTFers", the training book from Nu1L, one of China's strongest CTF teams. Part 1 was the overview, Part 2 covered web, and Part 3 covered reverse engineering and PWN. This part covers cryptography, the category that scares people off because it looks like maths. The book's point is that CTF crypto is rarely about breaking real ciphers. It is about spotting the one mistake in how a cipher was used, and the named attack that undoes it.
Summary
CTF crypto splits cleanly. Encoding is a transform with no key, so you just recognise it and reverse it. Classical ciphers are a warm-up. The real work is in symmetric crypto, where a mode or a weak keystream leaks the plaintext, and in public-key crypto, where RSA falls to a long list of named attacks when its parameters are chosen badly.
The book makes one point worth keeping. The named-attack challenges are the easy ones. If you are handed a public key with a tiny private exponent, the attack is Wiener's and the work is done for you. The hard challenges hand you a custom scheme with no name, and there the only thing that helps is understanding the maths well enough to build the attack yourself. Below is the map, from encoding to elliptic curves.
The territory
The book runs encoding first, then classical, symmetric, and public-key crypto. Here is the whole map before the detail.
| # | Technique | What it does | Tools |
|---|---|---|---|
| 1 | Encoding | Recognises and reverses a keyless transform | CyberChef, Ciphey |
| 2 | Classical ciphers | Breaks Caesar, Vigenere, substitution, transposition | CyberChef, Ciphey |
| 3 | Block cipher modes | Exploits ECB pattern leaks and mode mistakes | Python |
| 4 | AES as linear algebra | Solves an AND/XOR cipher as a system over GF(2) | SageMath |
| 5 | Stream ciphers | Predicts a weak keystream (LCG, glibc rand) | Python |
| 6 | LFSR | Recovers the taps from known output bits | SageMath |
| 7 | RC4 | Recovers the keystream from known plaintext | Python |
| 8 | RSA factorization | Factors a weak or close-prime modulus | factordb, Yafu, SageMath |
| 9 | RSA low exponent | Cube root, common modulus, Hastad broadcast | gmpy2, SageMath |
| 10 | RSA Wiener | Recovers a small private exponent | Python, SageMath |
| 11 | RSA Coppersmith and LSB oracle | Uses partial knowledge or a parity oracle | SageMath |
| 12 | Discrete log and ECC | Solves the discrete log when the group is weak | SageMath |
Encoding and classical: the warm-up
Encoding
Encoding is not encryption. There is no key, only a transform everyone knows, so the whole job is recognising which one and reversing it. The Base family is the common one: Base64 turns three bytes into four printable characters and pads with =, Base32 uses A-Z2-7, Base16 is hex. Around them sit uuencode, xxencode, URL percent-encoding, and the JavaScript oddities jjencode and aaencode that render code as symbols or emoticons.
telltales:
ends with = or ==, chars A-Za-z0-9+/ -> Base64
only A-Z and 2-7 -> Base32
%41%42%43 -> URL encoding
a long string of )(][!+ and nothing else -> jjencode (JS)
Do not identify these by eye for long. CyberChef's Magic operation and Ciphey both detect and peel nested encodings for you, which is the point: encoding challenges are a speed bump, not a puzzle.
Classical ciphers
Classical ciphers are substitution or transposition with a tiny key space. Caesar shifts every letter by a fixed amount, so 25 shifts brute-force it. Vigenere is a repeating-key Caesar, broken by finding the key length first with the Kasiski method (look for repeated substrings and take the spacing's common factors), then solving each slice as its own Caesar.
# Vigenere, once you have the key length, is frequency analysis per column.
# Let a tool do the search rather than hand-rolling it:
ciphey -t "Lxfopv ef rnhr" # auto-detects and cracks common classical ciphers
Substitution ciphers like Bacon (each letter as five A/B bits, often hidden in formatting) and Pigpen (grid symbols) are pattern recognition. Transposition ciphers like the rail fence rearrange letters without changing them, so the letter frequencies look like plain text but the order is scrambled. The book's own line is that classical ciphers are rarely the core of a modern CTF, so recognise them fast and move on.
Symmetric crypto: modes and keystreams
Block cipher modes
A block cipher is only as strong as its mode. ECB encrypts each block on its own, so identical plaintext blocks give identical ciphertext blocks, which leaks structure and lets you copy and paste blocks. The famous picture of an encrypted image where you can still see the shape is ECB. CBC, CFB, OFB, and CTR chain blocks to hide that, but each has its own failure when the IV or counter is reused.
# ECB tell: find a repeated 16-byte block in the ciphertext
ct = bytes.fromhex(hex_ciphertext)
blocks = [ct[i:i+16] for i in range(0, len(ct), 16)]
print(len(blocks) != len(set(blocks))) # True means ECB with repeated plaintext
The CBC attacks (bit-flipping, the padding oracle, IV recovery) show up constantly, but they appeared in the web part of this series because that is where the book puts them. Keep a padding-oracle solver template ready; the book says it appears far more often than any other block attack.
AES as linear algebra
AES itself does not break, but custom ciphers built to look like it do. The CTF insight the book teaches is that XOR is addition and AND is multiplication in GF(2), the field of one-bit numbers. So any cipher built only from AND and XOR is a linear system, and a linear system is solved by inverting a matrix, no matter how many rounds it has.
# SageMath: an AND/XOR cipher over n bits is a linear map over GF(2).
# Build the matrix from the cipher, then invert it.
M = matrix(GF(2), rows) # each row is the cipher's effect on one input bit
sol = M.solve_right(vector(GF(2), target_bits))
The book's case is Magic from SUCTF 2018, a 256-variable system solved exactly this way in SageMath. The lesson generalises: when a cipher is linear, you never brute-force it, you solve it.
Stream ciphers
A stream cipher XORs the plaintext with a keystream, so its security is entirely the randomness of the keystream generator. Weak generators are predictable. A linear congruential generator (x = (A*x + B) mod M) is recoverable from a few consecutive outputs, and glibc's rand() is a linear feedback that you can predict forward from past outputs.
# LCG: with M known and two consecutive outputs, solve for A and B.
A = (x2 - x3) * pow(x1 - x2, -1, M) % M
B = (x2 - A * x1) % M
# now you can predict every future value the server will use as a keystream
The takeaway is that a stream cipher with a bad PRNG is not a crypto problem, it is a prediction problem. Recover the generator's state and the keystream is yours.
LFSR
A linear feedback shift register produces a keystream by XORing fixed tap positions each step. Because every output bit is a linear combination of the initial state, 2n known output bits give you a linear system over GF(2) that recovers the taps and the seed. Same idea as the AES case: linear means solvable.
# with 2n output bits known, each bit is a GF(2) equation in the n state bits.
M = matrix(GF(2), equations)
state = M.solve_right(vector(GF(2), known_bits)) # recovered seed and taps
RC4
RC4 has no IV in its basic form, so if a key is reused across two messages the same keystream encrypts both, and the XOR of the two ciphertexts is the XOR of the two plaintexts with the key gone. With one known plaintext you recover the keystream outright and decrypt everything else encrypted under it.
keystream = xor(known_plaintext, its_ciphertext) # key cancels out
secret = xor(other_ciphertext, keystream) # decrypt the reuse
Public key: RSA and discrete logs
RSA factorization
RSA rests on n = p*q being hard to factor. When the challenge author picks bad primes, it is not. A small n is already in factordb or falls to Yafu in seconds. The sharper case is when p and q are close together: Fermat's method factors it almost instantly, because n sits just below a perfect square.
from gmpy2 import isqrt, is_square
a = isqrt(n) + 1
while not is_square(a*a - n): # close primes means only a few steps
a += 1
b = isqrt(a*a - n)
p, q = a + b, a - b # recovered the factors, private key follows
Once you have p and q, the private key is routine: phi = (p-1)*(q-1), d = inverse(e, phi), and you decrypt. The whole attack is getting the factors.
RSA low exponent
A small public exponent is its own weakness. With e = 3 and a short message, m^3 is smaller than n, so no modular wrap happens and the plaintext is a plain cube root. Two more attacks need no private key at all: common modulus (the same m sent under the same n with two coprime exponents) recovers m by Bezout, and Hastad's broadcast (the same m sent to three people with e = 3) recovers it by the Chinese remainder theorem.
# common modulus: same n, coprime e1/e2, same m, no factoring needed
g, a, b = gmpy2.gcdext(e1, e2) # a*e1 + b*e2 = 1
m = pow(c1, a, n) * pow(c2, b, n) % n # recovered plaintext
RSA Wiener
When the private exponent d is small (below the fourth root of n), the public exponent e is correspondingly huge, and that is the tell. Wiener's attack expands e/n as a continued fraction; one of its convergents is k/d, and testing each convergent recovers d directly.
# the convergents of e/n include k/d; test each as a candidate private key
for k, d in convergents(e, n):
if d and (e*d - 1) % k == 0:
phi = (e*d - 1) // k
# solve for p, q from n and phi; if they're integers, d is correct
A giant e paired with a normal n is the signal to reach for Wiener's first. RsaCtfTool runs it automatically, but the book's point stands: know why it works.
RSA Coppersmith and the LSB oracle
The deeper attacks use partial knowledge. Coppersmith's method recovers a message when you already know most of its bits, by framing the unknown as a small root of a polynomial mod n and finding it with the LLL lattice-reduction algorithm. A decryption oracle that leaks only the last bit of a chosen ciphertext is just as fatal: multiply the ciphertext by 2^e and the parity of the decryption tells you which half of the range the plaintext is in, so you binary-search the whole message in about log2(n) queries.
# LSB oracle: each query halves the search interval
lo, hi = 0, n
for _ in range(n.bit_length()):
c = (c * pow(2, e, n)) % n
if oracle_is_odd(c): lo = (lo + hi) // 2 # parity narrows the range
else: hi = (lo + hi) // 2
# hi is the recovered plaintext
Discrete log and ECC
The other public-key family rests on the discrete logarithm: given y = g^x mod p, recover x. It is hard in a strong group and easy in a weak one. Elliptic-curve crypto is the same problem on points of a curve. SageMath is the tool, and which function to call depends on the group: baby-step giant-step for small orders, Pohlig-Hellman when the group order has only small prime factors, and Pollard's rho otherwise.
# SageMath picks the right algorithm; it is fast when p-1 has no large prime factor
x = discrete_log(Mod(y, p), Mod(g, p)) # multiplicative group
x = discrete_log(Q, P, operation='+') # same call for an elliptic curve
The pattern across all of public-key crypto is the same as the symmetric side. The cipher is sound; the parameters are not. Read what you are given (the size of e, the shape of n, whether an oracle leaks a bit) and the given values name the attack.
Practice beats theory
1. Encoding is not a puzzle. If there is no key, it is a transform, and a tool reverses it in one step. Do not spend ten minutes recognising Base32 by eye when CyberChef's Magic does it instantly. Save the thinking for the parts that need it.
2. The named attack is the easy mode. A tiny d means Wiener, close primes mean Fermat, e = 3 means a cube root. Half of CTF crypto is matching the parameters you were handed to the attack that undoes them. Learn the list of tells.
3. Learn the maths, not the tool. RsaCtfTool will try every named RSA attack for you, and it should be your first move. But the challenges that decide a competition hand you a scheme with no name, where the only thing that helps is building the lattice or the linear system yourself. The tools run out; the maths does not.
Prepare for CTF with CyberLearner
The named RSA attacks and more have hands-on labs on CyberLearner for free.
- Sentinel. Wiener's attack on an RSA key with a small private exponent, the exact continued-fraction recovery above.
- Courier. Fermat factorisation of a modulus with close primes, delivered across shuffled QR codes you reassemble first.
- Blackbox. A chained challenge that brute-forces a weak signing secret, then decrypts an AES-CBC vault, crypto used the way it breaks in practice.
Browse the full set on the challenges page.
Next
Part 5 moves to forensics and misc: Part 5: forensics and misc.
Sources
- Nu1L team profile on CTFtime
- Twenty Years of Attacks on the RSA Cryptosystem, Dan Boneh
- SageMath documentation
- RsaCtfTool, automated RSA attack suite