defmod_center(x: int, modulus: int) -> int: x %= modulus if x > modulus // 2: x -= modulus return x
defcenter_lift(poly: list[int], modulus: int) -> list[int]: return [mod_center(x, modulus) for x in poly]
defpoly_add(a: list[int], b: list[int], n: int, modulus: int | None = None) -> list[int]: out = [(_trim(a, n)[i] + _trim(b, n)[i]) for i inrange(n)] if modulus isnotNone: out = [x % modulus for x in out] return out
defpoly_mul(a: list[int], b: list[int], n: int, modulus: int | None = None) -> list[int]: a = _trim(a, n) b = _trim(b, n) out = [0] * n for i, ai inenumerate(a): if ai == 0: continue for j, bj inenumerate(b): if bj: out[(i + j) % n] += ai * bj if modulus isnotNone: out = [x % modulus for x in out] return out
def_solve_mod(matrix: list[list[int]], target: list[int], modulus: int) -> list[int]: n = len(target) aug = [[matrix[r][c] % modulus for c inrange(n)] + [target[r] % modulus] for r inrange(n)] row = 0 for col inrange(n): pivot = None for r inrange(row, n): if aug[r][col] % modulus: pivot = r break if pivot isNone: continue aug[row], aug[pivot] = aug[pivot], aug[row] inv = _inv_mod(aug[row][col], modulus) aug[row] = [(v * inv) % modulus for v in aug[row]] for r inrange(n): if r == row: continue factor = aug[r][col] % modulus if factor: aug[r] = [(aug[r][c] - factor * aug[row][c]) % modulus for c inrange(n + 1)] row += 1 if row != n: raise ValueError("polynomial is not invertible") return [aug[i][-1] % modulus for i inrange(n)]
defpoly_inv(poly: list[int], n: int, modulus: int) -> list[int]: poly = _trim(poly, n) matrix = [[poly[(r - c) % n] for c inrange(n)] for r inrange(n)] target = [1] + [0] * (n - 1) inv = _solve_mod(matrix, target, modulus) if poly_mul(inv, poly, n, modulus) != target: raise ValueError("inverse verification failed") return inv
defkeygen(params: NTRUParams, rng: random.Random) -> tuple[PublicKey, PrivateKey]: whileTrue: F = sample_sparse_ternary(params.N, params.df, rng, avoid_zero=True) G = sample_sparse_ternary(params.N, params.dg, rng) f = [0] * params.N f[0] = 1 f = poly_add(f, [params.p * x for x in F], params.N) g = [params.p * x for x in G] try: finv_q = poly_inv(f, params.N, params.q) except ValueError: continue h = poly_mul(finv_q, g, params.N, params.q) return PublicKey(h), PrivateKey(f, g)
defdecrypt(ciphertext: list[int], private_key: PrivateKey, params: NTRUParams) -> list[int]: lifted = center_lift(poly_mul(private_key.f, ciphertext, params.N, params.q), params.q) return [x % params.p for x in lifted]
defbytes_to_poly_blocks(data: bytes, n: int, chunk_bytes: int) -> list[list[int]]: if3**n <= 256**chunk_bytes: raise ValueError("chunk_bytes is too large for this polynomial degree") payload = len(data).to_bytes(2, "big") + data blocks = [] for start inrange(0, len(payload), chunk_bytes): chunk = payload[start : start + chunk_bytes] value = int.from_bytes(chunk, "little") trits = [] for _ inrange(n): trits.append(value % 3) value //= 3 if value: raise ValueError("chunk does not fit into one polynomial") blocks.append(trits) return blocks
defpoly_blocks_to_bytes(blocks: list[list[int]], chunk_bytes: int) -> bytes: raw = bytearray() for block in blocks: value = 0 for coeff inreversed(block): value = value * 3 + (coeff % 3) raw.extend(value.to_bytes(chunk_bytes, "little")) iflen(raw) < 2: raise ValueError("missing length prefix") size = int.from_bytes(raw[:2], "big") returnbytes(raw[2 : 2 + size])
defmod_center(x: int, modulus: int) -> int: x %= modulus if x > modulus // 2: x -= modulus return x
defcenter_lift(poly: list[int], modulus: int) -> list[int]: return [mod_center(x, modulus) for x in poly]
defpoly_add(a: list[int], b: list[int], n: int, modulus: int | None = None) -> list[int]: out = [(_trim(a, n)[i] + _trim(b, n)[i]) for i inrange(n)] if modulus isnotNone: out = [x % modulus for x in out] return out
defpoly_mul(a: list[int], b: list[int], n: int, modulus: int | None = None) -> list[int]: a = _trim(a, n) b = _trim(b, n) out = [0] * n for i, ai inenumerate(a): if ai == 0: continue for j, bj inenumerate(b): if bj: out[(i + j) % n] += ai * bj if modulus isnotNone: out = [x % modulus for x in out] return out
def_solve_mod(matrix: list[list[int]], target: list[int], modulus: int) -> list[int]: n = len(target) aug = [[matrix[r][c] % modulus for c inrange(n)] + [target[r] % modulus] for r inrange(n)] row = 0 for col inrange(n): pivot = None for r inrange(row, n): if aug[r][col] % modulus: pivot = r break if pivot isNone: continue aug[row], aug[pivot] = aug[pivot], aug[row] inv = _inv_mod(aug[row][col], modulus) aug[row] = [(v * inv) % modulus for v in aug[row]] for r inrange(n): if r == row: continue factor = aug[r][col] % modulus if factor: aug[r] = [(aug[r][c] - factor * aug[row][c]) % modulus for c inrange(n + 1)] row += 1 if row != n: raise ValueError("polynomial is not invertible") return [aug[i][-1] % modulus for i inrange(n)]
defpoly_inv(poly: list[int], n: int, modulus: int) -> list[int]: poly = _trim(poly, n) matrix = [[poly[(r - c) % n] for c inrange(n)] for r inrange(n)] target = [1] + [0] * (n - 1) inv = _solve_mod(matrix, target, modulus) if poly_mul(inv, poly, n, modulus) != target: raise ValueError("inverse verification failed") return inv
defkeygen(params: NTRUParams, rng: random.Random) -> tuple[PublicKey, PrivateKey]: whileTrue: F = sample_sparse_ternary(params.N, params.df, rng, avoid_zero=True) G = sample_sparse_ternary(params.N, params.dg, rng) f = [0] * params.N f[0] = 1 f = poly_add(f, [params.p * x for x in F], params.N) g = [params.p * x for x in G] try: finv_q = poly_inv(f, params.N, params.q) except ValueError: continue h = poly_mul(finv_q, g, params.N, params.q) return PublicKey(h), PrivateKey(f, g)
defdecrypt(ciphertext: list[int], private_key: PrivateKey, params: NTRUParams) -> list[int]: lifted = center_lift(poly_mul(private_key.f, ciphertext, params.N, params.q), params.q) return [x % params.p for x in lifted]
defbytes_to_poly_blocks(data: bytes, n: int, chunk_bytes: int) -> list[list[int]]: if3**n <= 256**chunk_bytes: raise ValueError("chunk_bytes is too large for this polynomial degree") payload = len(data).to_bytes(2, "big") + data blocks = [] for start inrange(0, len(payload), chunk_bytes): chunk = payload[start : start + chunk_bytes] value = int.from_bytes(chunk, "little") trits = [] for _ inrange(n): trits.append(value % 3) value //= 3 if value: raise ValueError("chunk does not fit into one polynomial") blocks.append(trits) return blocks
defpoly_blocks_to_bytes(blocks: list[list[int]], chunk_bytes: int) -> bytes: raw = bytearray() for block in blocks: value = 0 for coeff inreversed(block): value = value * 3 + (coeff % 3) raw.extend(value.to_bytes(chunk_bytes, "little")) iflen(raw) < 2: raise ValueError("missing length prefix") size = int.from_bytes(raw[:2], "big") returnbytes(raw[2 : 2 + size])
withopen("public_key.txt") as f: exec(f.read()) withopen("output.txt") as f: exec(f.read()) params = NTRUParams(N=N, p=p, q=q)
# 构建循环矩阵 H H = [h[-i:] + h[:-i] if i else h for i inrange(N)] L = block_matrix( ZZ, [[identity_matrix(N), matrix(H)], [zero_matrix(N), q * identity_matrix(N)]] ) L = L.BKZ(block_size=20)
privK = None for row in L.rows(): # 取目标向量 (f, g) 中的 f v = list(row[:N]) # f 的长度平方最大值为 64 if0 < sum(x * x for x in v) <= 64: # 处理反转 for sign in [-1, 1]: cur = [sign * x for x in v] # 循环移位 x^s * f(x) 得到的向量长度可能相同,需要全部遍历 for s inrange(N): cand = cur[-s:] + cur[:-s] if s else cur # 校验是否满足 f = 3F + 1 的特征,即常数项为 1 if [x % 3for x in cand] == [1] + [0] * (N - 1): privK = PrivateKey(f=cand, g=[]) break
blocks = [decrypt(c, privK, params) for c in ciphertexts] print(poly_blocks_to_bytes(blocks, params.chunk_bytes).decode()) ''' flag{27dec48f-f9c7-4bad-9a1b-f7aa77badc5f} [Done] exited with code=0 in 72.721 seconds '''
defextract(id, nums=8): lag = lags[id] A_list, B_list = [], []
for t in [t for t in data["transcripts"] if t["signer"] == id][:nums]: c = int(t["challenge"], 16) z = int(t["z"], 16) nonce_msb = int(t["nonce_msb"], 16)
Ai = (-lag * c) % q Bi = (z - nonce_msb * shift) % q
A_list.append(Ai) B_list.append(Bi)
return A_list, B_list
defsolve_LLL(A_list, B_list): C = shift n = len(A_list)
M = Matrix(ZZ, n + 2, n + 1) for i inrange(n): M[i, i] = q M[n, i] = A_list[i] M[n + 1, i] = B_list[i] M[n + 1, n] = C
M = M.LLL()
for row in M: ifabs(row[-1]) == C: sign = 1if row[-1] == C else -1 delta_0 = sign * row[0]
s = ((delta_0 - B_list[0]) * inverse_mod(A_list[0], q)) % q return s
classCurve: def__init__(self, p, a, b): self.p = p self.a = a % p self.b = b % p
defis_on_curve(self, P): if P.is_infinity(): returnTrue ifnot (0 <= P.x < self.p and0 <= P.y < self.p): returnFalse left = (P.y * P.y) % self.p right = (pow(P.x, 3, self.p) + self.a * P.x + self.b) % self.p return left == right
defadd(self, P, Q): if P.is_infinity(): return Q if Q.is_infinity(): return P
p = self.p x1, y1 = P.x % p, P.y % p x2, y2 = Q.x % p, Q.y % p
if x1 == x2 and (y1 + y2) % p == 0: return O
try: if x1 == x2 and y1 == y2: den = (2 * y1) % p if den == 0: return O lam = ((3 * x1 * x1 + self.a) * pow(den, -1, p)) % p else: den = (x2 - x1) % p lam = ((y2 - y1) * pow(den, -1, p)) % p except ValueError as exc: raise InvalidPoint("non-invertible denominator") from exc
defneg(self, P): if P.is_infinity(): return P return Point(P.x, (-P.y) % self.p)
defmul(self, k, P): if k < 0: returnself.mul(-k, self.neg(P)) result = O addend = P while k: if k & 1: result = self.add(result, addend) addend = self.add(addend, addend) k >>= 1 return result
defint_to_bytes(n): if n == 0: returnb"\x00" return n.to_bytes((n.bit_length() + 7) // 8, "big")
defsqrt_mod_p_3_mod_4(n, p): y = pow(n % p, (p + 1) // 4, p) if (y * y) % p != n % p: returnNone return y
defload_secret(): value = os.environ.get("SERVER_D") if value: returnint(value, 0) for path in ("server_secret.txt", "/app/server_secret.txt", "/flag_server_secret.txt"): if os.path.exists(path): withopen(path, "r", encoding="utf-8") as f: returnint(f.read().strip(), 0) raise RuntimeError("server secret is not configured")
defload_flag(): value = os.environ.get("FLAG") if value: return value.encode() for path in ("/flag", "/app/flag"): if os.path.exists(path): withopen(path, "rb") as f: return f.read().strip() returnb"local dynamic flag placeholder"
classOracle: def__init__(self, secret_d=None, flag=None, max_queries=params.MAX_QUERIES): self.secret_d = load_secret() if secret_d isNoneelse secret_d self.flag = load_flag() if flag isNoneelse flag self.flag_iv, self.flag_ct = encrypt_flag(self.secret_d, self.flag) self.max_queries = max_queries self.used = 0 self.curve = Curve(params.P, params.A, params.B)
defquery(self, x, y): ifself.used >= self.max_queries: raise InvalidPoint("query limit exceeded") ifnot (0 <= x < params.P and0 <= y < params.P): raise InvalidPoint("coordinate out of range")
self.used += 1 peer = Point(x, y)
# Vulnerability: the implementation never calls self.curve.is_on_curve(peer). shared = self.curve.mul(self.secret_d, peer) key = derive_key(shared) iv = get_random_bytes(16) ct = AES.new(key, AES.MODE_CBC, iv).encrypt(pad(params.KNOWN_PLAINTEXT, 16)) return OracleResponse(iv, ct)
defmain(): oracle = Oracle() print("Welcome to Broken ECDH.") print(render_public_output(oracle.flag_iv, oracle.flag_ct)) print(f"You have {params.MAX_QUERIES} oracle queries.") print("Send your peer public key as: x y") sys.stdout.flush()
defadd(A, B): if A == O: return B if B == O: return A x1, y1 = A x2, y2 = B if x1 == x2 and (y1 + y2) % P == 0: return O if x1 == x2 and y1 == y2: den = 2 * y1 % P if den == 0: return O lam = 3 * x1 * x1 * pow(den, -1, P) % P else: lam = (y2 - y1) * pow((x2 - x1) % P, -1, P) % P x3 = (lam * lam - x1 - x2) % P y3 = (lam * (x1 - x3) - y1) % P return (x3, y3)
defmul(k, A): R, T = O, A while k: if k & 1: R = add(R, T) T = add(T, T) k >>= 1 return R
defint_to_bytes(n): if n == 0: returnb"\x00" return n.to_bytes((n.bit_length() + 7) // 8, "big")
defrandom_point(): whileTrue: x = random.randrange(2, P) rhs = (x * x * x + 7) % P y = pow(rhs, (P + 1) // 4, P) if y * y % P == rhs: return (x, y)
defsmall_prime_factors(m): fs, t, d = [], m, 2 while d * d <= t: if t % d == 0: fs.append(d) while t % d == 0: t //= d d += 1 if t > 1: fs.append(t) return fs
defpoint_of_order(m): # E(F_p) 是 p+1 阶循环群,随机点缩阶即可得到任意 m | p+1 阶的点 whileTrue: T = mul((P + 1) // m, random_point()) if T == O or mul(m, T) != O: continue ifall(mul(m // l, T) != O for l in small_prime_factors(m)): return T
defcrt(rs, ms): x, M = 0, 1 for r, m inzip(rs, ms): x += M * ((r - x) * pow(M, -1, m) % m) M *= m return x
# 1) 对每个模数 m 提交阶为 m 的点,爆破 d mod m residues = [] for m in ORDERS: T = point_of_order(m) io.sendline(f"{T[0]}{T[1]}".encode()) line = io.recvline().decode().strip() if line == "invalid": # d*T = O(derive_key 抛异常)=> m | d residues.append(0) print(f"[+] d mod {m} = 0 (invalid)") continue iv = bytes.fromhex(line.split("= ")[1]) ct = bytes.fromhex(io.recvline().decode().strip().split("= ")[1]) for k inrange(1, m): pt = AES.new(derive_key(mul(k, T)), AES.MODE_CBC, iv).decrypt(ct) if pt.startswith(KNOWN): residues.append(k) print(f"[+] d mod {m} = {k}") break
# 3) 用 d 计算真实共享点,解密 flag shared = mul(d, B_pub) flag = unpad(AES.new(derive_key(shared), AES.MODE_CBC, flag_iv).decrypt(flag_ct), 16) print(f"[+] flag = {flag.decode()}")