THE LATTICE SECRET
Mathematic
Attachments
Recon
The handout secret.zip unpacks into a generator chall.py and the instance it produced, challenge.json. The generator hardcodes 40 public weights of about 100 bits each, a target sum and a 31-byte encrypted_flag, then dumps all of it to JSON. The JSON metadata names the intended technique, "technique": "LLL / Subset Sum", but nothing documents how the flag was encrypted, so the challenge splits in two: recover the secret 0/1 selection with a lattice reduction, then work out how that selection becomes a key. One quirk of the shipped file: challenge.json is truncated, ending right after the encrypted_flag string with no closing brace, so every parser call in our scripts appends the missing } by hand.
The instance is a subset-sum problem: find a bit vector x in {0,1}^40 with sum(w_i * x_i) == target. The number that decides which attack applies is the density, d = n / log2(max weight). Instances with density below about 0.9408 fall to lattice reduction, and this one is far below it.
$ python3 -c '
import json
data = json.loads(open("challenge.json").read() + "}")
w, t = data["weights"], data["target"]
print("technique:", data["technique"])
print("n =", len(w))
print("max weight bits =", max(w).bit_length())
print("density =", len(w) / max(w).bit_length())
print("target / total sum =", t / sum(w))
print("encrypted_flag bytes =", len(bytes.fromhex(data["encrypted_flag"])))
'
technique: LLL / Subset Sum
n = 40
max weight bits = 100
density = 0.4
target / total sum = 0.4292205490378723
encrypted_flag bytes = 31
A density of 0.4 is well inside the lattice-friendly range, so we skipped meet-in-the-middle and attacked the lattice directly. The target is about 43% of the total weight sum, which says roughly 17 of the 40 weights are selected, and the ciphertext is exactly 31 bytes, so we expect a 31-byte flag with no padding.
Exploitation
Building the lattice
LLL (Lenstra-Lenstra-Lovász reduction) takes a lattice, the set of all integer combinations of a set of basis vectors, and returns a new basis of the same lattice whose rows are much shorter. To use it we need a basis in which the subset-sum answer is a very short vector. We used the CJLOSS construction (Coster-Joux-LaMacchia-Odlyzko), the one that provably handles densities up to 0.9408 where the older Lagarias-Odlyzko basis caps out at 0.6463.
The basis is a 41x41 integer matrix M with a scaling factor N:
- rows 0 to 39, one per weight: entry
2in its own columni, andN * w_iin the last column; - row 40: entry
1in each of the first 40 columns, andN * targetin the last column.
Now take the particular integer combination v = sum(x_i * row_i) - row_40, where x is the answer. Its first 40 coordinates are 2*x_i - 1, so +1 where x_i = 1 and -1 where x_i = 0. Its last coordinate is N * (sum(x_i * w_i) - target), which is 0 because x solves the instance. The norm of v is sqrt(40), about 6.32.
Why nothing else gets that short: the last coordinate of any lattice vector is a multiple of N, so a nonzero one forces a norm of at least N. We pick N = 16, comfortably above 6.32, so any competitor must also have last coordinate 0, meaning its coefficients satisfy another exact subset-sum relation sum(a_i * w_i) == -b * target. Among those, the coefficient b of row 40 decides parity, since every entry is 2*a_i + b: if b is odd, all 40 entries are odd and nonzero, so the norm is at least sqrt(40) with equality only for another all-±1 vector that also solves the instance (a second solution, which a random instance does not have). If b is even, a vector shorter than sqrt(40) would be a very short integer relation among the 100-bit weights, which a random instance also does not have. So v, up to sign, is the shortest vector of the lattice, and LLL surfaces it as one of the first rows of the reduced basis.
The factor 2 comes from the CJLOSS centering trick. The original construction adds 1/2 to each 0/1 variable so the target vector has balanced ±1/2 entries, and multiplying the whole basis by 2 keeps the matrix integral (entries 2 and 1) without changing which vectors are short. That centering is what buys the improved density bound.
Reduction and readout
The readout rule: scan every reduced row for one with last coordinate 0 and all 40 first entries in {-1, +1}, map bits with x_i = (v_i + 1) / 2 testing both the row and its negation, and accept a candidate only when recomputing sum(w_i * x_i) reproduces the target exactly. The script tries N = 2^4 up to max(w) as a ladder, in case a small N lets a nonzero-sum vector compete.
#!/usr/bin/env sage
# CJLOSS lattice attack on the subset-sum instance
import json
try:
data = json.load(open("challenge.json"))
except json.JSONDecodeError:
# the shipped copy is truncated, missing the final "}"
data = json.loads(open("challenge.json").read() + "}")
w = [Integer(x) for x in data["weights"]]
target = Integer(data["target"])
n = len(w)
print("n =", n, "density = %.3f" % (n / float(max(w).nbits())))
found = None
for Nmult in [2**4, 2**8, 2**12, 2**16, 2**32, max(w)]:
M = matrix(ZZ, n + 1, n + 1)
for i in range(n):
M[i, i] = 2
M[i, n] = Nmult * w[i]
for j in range(n):
M[n, j] = 1
M[n, n] = Nmult * target
B = M.LLL()
for row in B:
if row[n] != 0 or not all(abs(row[i]) == 1 for i in range(n)):
continue
for sign in (1, -1):
x = [(sign * row[i] + 1) // 2 for i in range(n)]
if sum(wi * xi for wi, xi in zip(w, x)) == target:
found = x
print("SOLUTION found with Nmult =", Nmult)
break
if found:
break
if found:
break
if found:
sol = "".join(str(b) for b in found)
print("bits =", sol)
print("count1 =", sum(found))
print("verify sum:", sum(wi * xi for wi, xi in zip(w, found)), "==", target)
val = int(sol, 2)
print("packed_be =", val.to_bytes(5, "big").hex())
print("indices =", [i for i, b in enumerate(found) if b])
open("solution.txt", "w").write(sol)
$ sage lattice_solve.sage
n = 40 density = 0.400
SOLUTION found with Nmult = 16
bits = 1100101010010011010010010010001001100110
count1 = 17
verify sum: 16657604446079629519682967403218 == 16657604446079629519682967403218
packed_be = ca93492266
indices = [0, 1, 4, 6, 8, 11, 14, 15, 17, 20, 23, 26, 30, 33, 34, 37, 38]
The first ladder value already solved it. The selection has 17 elements, matching the 43% estimate from recon, and the recomputed sum equals the target exactly, so the 40-bit secret is 1100101010010011010010010010001001100110. The original script also carried a BKZ(block_size=25) fallback for the case where the whole ladder failed; it never ran, so we omit it here.
Working out the key derivation
The generator never says how the flag was encrypted, so this half is a search over candidate constructions, each checked locally against the flag format. If it is a stream-style XOR, the flag format forces the first four keystream bytes, since CT[0:4] ^ "NVR{" = ca 5e 07 c6. Any key hypothesis that does not start with those bytes is dead, and any decryption whose remaining 27 bytes are not printable ASCII is dead too.
The handout’s chall.py contains no encryption code to read, so there is no single obvious construction to try, and there is no server and no rate limit, so every candidate settles in microseconds. One script can therefore answer the whole standard space in a single run, and the first pass enumerated it starting from the object in hand and working outward: the bit string as ASCII in both directions, big/little-endian packings into 5 and 8 bytes, the selected indices as a list and as CSV, then hashes of each of those as repeating keys, Python random pads seeded with the solution, and RC4, AES and ChaCha20 keyed by every candidate. Nothing hit, and the diagnostic tail printed the numbers we needed next (key_hunt.py is the earlier, narrower version of the script below; we do not reprint it since the second pass repeats its method with a wider material list):
$ python3 key_hunt.py | tail -4
total hits: 0
required keystream prefix: ca5e07c6 = [202, 94, 7, 198]
sol bits: 1100101010010011010010010010001001100110
packed_be5: ca93492266
The plain big-endian packing of the selection is ca 93 49 22 66, and its first byte 0xca is exactly the first forced keystream byte. That is a 1-in-256 coincidence, but it pointed at the packing family as key material. The raw packing cannot be the repeating key itself, because a 5-byte repeating key reuses key[0] = 0xca at plaintext index 5, and CT[5] ^ 0xca = 0x7c ^ 0xca = 0xb6 is outside printable ASCII. So the second pass kept the packings, added bit-order variants (whole-string reversal, all 40 rotations) and hash chains (digest of the digest, concatenated past 31 bytes), and hashed every material with the standard families. Here is the core of it:
#!/usr/bin/env python3
# Second key-derivation hunt. A hit needs pt[:4] == b"NVR{"
# and printable ASCII in the rest. Hits print the tag only.
import hashlib
CT = bytes.fromhex("840855bdee7cfc34f8745cec9ab417972f28dac36c0c59947ab7bff5ae8525")
SOL = open("solution.txt").read().strip()
sol_int = int(SOL, 2)
ones = [i for i, b in enumerate(SOL) if b == "1"]
mats = {
"bits_ascii": SOL.encode(), "bits_ascii_rev": SOL[::-1].encode(),
"packed_be5": sol_int.to_bytes(5, "big"), "packed_le5": sol_int.to_bytes(5, "little"),
"packed_be8": sol_int.to_bytes(8, "big"),
"str_int": str(sol_int).encode(), "be5hex": sol_int.to_bytes(5, "big").hex().encode(),
"idx_list": str(ones).encode(), "idx_csv": ",".join(map(str, ones)).encode(),
}
bits_rev = SOL[::-1]
mats["packed_be5_bitsrev"] = bytes(int(bits_rev[i:i+8], 2) for i in range(0, 40, 8))
for r in range(40):
mats[f"rot{r}_be5"] = int(SOL[r:] + SOL[:r], 2).to_bytes(5, "big")
keys = {}
for name, m in mats.items():
for h in ("md5", "sha1", "sha256", "sha512", "sha3_256", "blake2s"):
keys[f"{h}({name})"] = hashlib.new(h, m).digest()
keys[f"{h}hex({name})"] = hashlib.new(h, m).hexdigest().encode()
def chain(m, hname, total):
out, d = b"", hashlib.new(hname, m).digest()
while len(out) < total:
out += d
d = hashlib.new(hname, d).digest()
return out[:total]
for name, m in mats.items():
for h in ("md5", "sha1", "sha256", "sha512"):
keys[f"chain-{h}({name})"] = chain(m, h, 40)
count = 0
for name, k in keys.items():
for mode, pt in [
("xor", bytes(c ^ k[i % len(k)] for i, c in enumerate(CT))),
("add", bytes((c + k[i % len(k)]) % 256 for i, c in enumerate(CT))),
("sub", bytes((c - k[i % len(k)]) % 256 for i, c in enumerate(CT))),
]:
count += 1
if pt[:4] == b"NVR{" and all(32 <= b < 127 for b in pt):
print("[HIT]", mode + "/" + name)
print(f"tested {count} decryptions")
$ python3 key_hunt2_core.py
[HIT] xor/sha256(packed_be5_bitsrev)
[HIT] xor/chain-sha256(packed_be5_bitsrev)
tested 2400 decryptions
Both hits land on the same material. The chain hit is not a second construction, because the first block of a SHA-256 chain is the plain digest itself, so the chain and the plain hash agree on the first 32 bytes and both cover the 31-byte ciphertext. The construction is SHA-256 over the bit-reversed packing. Concretely, packed_be5_bitsrev packs the reversed 40-bit string big-endian, which is the same as taking the plain packing ca 93 49 22 66, reversing the byte order and reversing the bits inside each byte: ca -> 53, 93 -> c9, 49 -> 92, 22 -> 44, 66 -> 66 (a palindrome), giving 66 44 92 c9 53.
Flag capture
The final decrypt packs the solution the same way, hashes it, truncates the 32-byte digest to the 31-byte ciphertext and XORs. The key starts with ca 5e 07 c6, exactly the forced prefix, so the full decrypt should land:
import hashlib
SOL = "1100101010010011010010010010001001100110"
CT = bytes.fromhex("840855bdee7cfc34f8745cec9ab417972f28dac36c0c59947ab7bff5ae8525")
packed_rev = bytes(int(SOL[i:i+8][::-1], 2) for i in range(32, -8, -8))[:5]
key = hashlib.sha256(packed_rev).digest()[:31]
flag = bytes(a ^ b for a, b in zip(CT, key))
print("packed (bit-reversed):", packed_rev.hex())
print("key (first 31 bytes):", key.hex())
print("FLAG:", flag.decode())
$ python3 decrypt_flag.py
packed (bit-reversed): 664492c953
key (first 31 bytes): ca5e07c6a230b06b9e1d3288e9eb63ff4a77a9ab037e2dcb0cd2dc81c1f758
FLAG: NVR{LLL_finds_the_short_vector}