from pathlib import Path import ast import re from sympy import Matrix
OUT = Path("output.txt") EMBED_K = 20
def parse_vector(text, name): match = re.search(rf"{name} = vector\(ZZ, \[(.*?)\]\)", text, re.S) if not match: raise ValueError(f"missing vector {name}") return ast.literal_eval("[" + match.group(1) + "]")
def parse_matrix_h(text): start = text.index("H = Matrix(ZZ, [") + len("H = Matrix(ZZ, [") end = text.index("\n])", start) return ast.literal_eval("[" + text[start:end] + "]")
def poly_mul_xj_mod(poly, shift, modulus_coeffs): n = len(modulus_coeffs) coeffs = [0] * (len(poly) + shift) for index, value in enumerate(poly): coeffs[index + shift] = value
while len(coeffs) > n: value = coeffs.pop() base = len(coeffs) - n if value: for index, mod_coeff in enumerate(modulus_coeffs): coeffs[base + index] -= value * mod_coeff return coeffs + [0] * (n - len(coeffs))
def multiplication_matrix(poly, modulus_coeffs): n = len(modulus_coeffs) columns = [poly_mul_xj_mod(poly, shift, modulus_coeffs) for shift in range(n)] return [[columns[col][row] for col in range(n)] for row in range(n)]
def recover_modulus_coeffs(H, n): reduced = Matrix(H).lll(delta=0.99) shortest = min((list(map(int, reduced.row(i))) for i in range(reduced.rows)), key=lambda row: sum(value * value for value in row)) if shortest[n] < 0: shortest = [-value for value in shortest] if shortest[n] != 1: raise ValueError(f"unexpected monic coefficient: {shortest[n]}") return shortest[:n]
def recover_secret(M, B, p): n = len(B) rows = []
for index in range(n): row = [0] * (2 * n + 1) row[index] = p rows.append(row)
for col in range(n): row = [0] * (2 * n + 1) for row_index in range(n): row[row_index] = M[row_index][col] row[n + col] = 1 rows.append(row)
rows.append(B + [0] * n + [EMBED_K]) reduced = Matrix(rows).lll(delta=0.99)
for row_index in range(reduced.rows): row = list(map(int, reduced.row(row_index))) if abs(row[-1]) != EMBED_K: continue sign = 1 if row[-1] > 0 else -1 error = [value // sign for value in row[:n]] secret = [-value // sign for value in row[n:2 * n]] if max(abs(value) for value in error) <= 3: return secret, error raise ValueError("embedded LLL did not find a valid short error vector")
def main(): text = OUT.read_text(encoding="utf-8") H = parse_matrix_h(text) A = parse_vector(text, "A") B = parse_vector(text, "B") n = int(re.search(r"\nn = (\d+)", text).group(1)) p = int(re.search(r"\np = (\d+)", text).group(1))
f_coeffs = recover_modulus_coeffs(H, n) M = multiplication_matrix(A, f_coeffs) secret, error = recover_secret(M, B, p)
for row_index in range(n): value = sum(M[row_index][col] * secret[col] for col in range(n)) + error[row_index] assert value % p == B[row_index]
flag = bytes(secret).rstrip(b"\x00").decode() print(flag)
if __name__ == "__main__": main()
|