Hackvent_2023/Day 23/decrypt.sage

59 lines
1.4 KiB
Python

import re
import random
from Crypto.Util.number import long_to_bytes
values = {}
with open("output.txt", "r") as f:
lines = f.read().split("\n")
values["sum"] = int(lines[0])
for line in lines[1:]:
match = re.match(r"(\w+)=(-?[0-9]+)", line)
values[match[1]] = int(match[2])
for y in range(0, 1000+1):
random.seed(y)
grade = random.choice([2,3])
a = random.randint(9999, 999999)
b = random.randint(8888, 888888)
c = random.randint(7777, 777777)
if a + b + c == values["sum"]:
print("[+] Found y:", y)
break
print("[+] a:", a)
print("[+] b:", b)
print("[+] c:", c)
print("[+] grade:", grade)
x = var("x", domain="integer")
if grade == 2:
y_x = a*x**2+b*x+c
if grade == 3:
d = random.randint(6666, 666666)
y_x = a*x**3+b*x**2+c*x+d
print("[+] d:", d)
print("[+] polynome:", y_x)
N = values["N"]
hint = values["hint"]
p = None
q = var("q")
for x in range(0,1000+1):
eq = (N/q)^3 - q^8 + y_x(x=x) == hint
solution = solve(eq, q, solution_dict=True)
if solution and q in solution[0]:
print("[+] Found x:", x)
q = int(solution[0][q])
p = N//q
break
if p is None:
print("[-] Could not find p and q")
exit()
phi_n = (p - 1) * (q - 1)
d = pow(values["e"], -1, phi_n)
pt = pow(values["encrypted"], d, values["N"])
flag = long_to_bytes(pt).decode()
print("[+] Flag:", flag)