1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398
| from sage.all import * import sys, re, time from pwn import *
def jacobiSymbol(a, n): a = int(a) % int(n); n = int(n); result = 1 while a != 0: while a % 2 == 0: a //= 2 if n % 8 in (3, 5): result = -result a, n = n, a if a % 4 == 3 and n % 4 == 3: result = -result a %= n return result if n == 1 else 0
WITNESSES = [ 1273076718476451754317013814127123029, 845257091632129340504606410993318513, 986506745201158482766197094546488559, 707012940092118175868299125612312793, 1213424722665355883998859353747948559, 1096649821936509780592216743717621961, 1203575152124577162570333987040475647, 1034195762268271985553343293758258647, 941579813597084827990555116503495071, 1160627089774708491508668155051404403, 836824746890078856005143966739466953, 799204280537044489268386103838528451, 1172614136539511046357433964488059979, 1305442193052048480095062472502986473, 770725442321657635681777052007000523, 1235844317457938473442373336659073467 ]
def check_isPrime(p): p = int(p) if p < 2 or p % 2 == 0: return False e = p // 2 for a in WITNESSES: if pow(a, e, p) != (jacobiSymbol(a, p) % p): return False return True
MIN_BOUND = 1393796574908163946345982392040522594123776
CM_CLASS1 = { -3: 0, -4: 1728, -7: -3375, -8: 8000, -11: -32768, -19: -884736, -43: -884736000, -67: -147197952000, -163: -262537412640768000 }
def solve_norm_eq(D0_neg, primes_list): """Solve x^2 + |D0|*y^2 = 4*prod(primes) by solving per-prime and combining via Brahmagupta-Fibonacci identity. Returns list of (x, y) with x^2 + |D0|*y^2 = 4*N.""" D = abs(D0_neg) Q = BinaryQF([1, 0, D])
per_prime = [] for p in primes_list: sol = Q.solve_integer(4 * int(p)) if sol is None: return [] per_prime.append((abs(int(sol[0])), abs(int(sol[1]))))
def combine_two(s1, s2): a, b = s1 c, d = s2 results = set() for sb in [1, -1]: for sd in [1, -1]: x = a*c - D*(b*sb)*(d*sd) y = a*(d*sd) + c*(b*sb) if x % 2 == 0 and y % 2 == 0: results.add((abs(x)//2, abs(y)//2)) return list(results)
combined = [per_prime[0]] for i in range(1, len(per_prime)): new_combined = [] for s1 in combined: new_combined.extend(combine_two(s1, per_prime[i])) combined = list(set(new_combined))
N = 1 for p in primes_list: N *= int(p) valid = [] for x, y in combined: if x*x + D*y*y == 4*N: valid.append((x, y)) return valid
print("[*] Searching for E with small CM discriminant prime p...") t0 = time.time()
L_start = int((MIN_BOUND // 6) ** (1/3)) + 1 L_start = L_start + (6 - L_start % 12) % 12
found = None E_count = 0
for L in range(L_start, L_start + 50000000000, 12): p1 = L + 1 p2 = 2*L + 1 p3 = 3*L + 1
if p1 % 3 == 0 or p2 % 3 == 0 or p3 % 3 == 0: continue if p1 % 5 == 0 or p2 % 5 == 0 or p3 % 5 == 0: continue if p1 % 7 == 0 or p2 % 7 == 0 or p3 % 7 == 0: continue if p1 % 11 == 0 or p2 % 11 == 0 or p3 % 11 == 0: continue if p1 % 13 == 0 or p2 % 13 == 0 or p3 % 13 == 0: continue
if not is_pseudoprime(p1): continue if not is_pseudoprime(p2): continue if not is_pseudoprime(p3): continue
n = p1 * p2 * p3 if n < MIN_BOUND: continue
ok = True for w in WITNESSES: if kronecker_symbol(w, p1) * kronecker_symbol(w, p2) * kronecker_symbol(w, p3) != 1: ok = False; break if not ok: continue
if not check_isPrime(n): continue
E_count += 1 E_val = n E_factors = [p1, p2, p3]
if E_count % 1 == 0: print(f" E #{E_count}: L={L}, E={E_val} ({time.time()-t0:.1f}s)", flush=True)
for D0, j_inv in CM_CLASS1.items(): sols = solve_norm_eq(D0, E_factors) if not sols: continue for x, y in sols: for t_candidate in [x + 2, -x + 2]: cp = int(E_val) - 1 + t_candidate if cp < int(MIN_BOUND): continue if abs(int(E_val) - cp) < 10: continue if t_candidate * t_candidate > 4 * cp: continue if not is_prime(cp): continue mov_ok = True for k in range(1, 1000): if pow(int(cp), k, int(E_val)) == 1: mov_ok = False; break if not mov_ok: continue found = { 'E': E_val, 'factors': E_factors, 'L': L, 'p': cp, 't': t_candidate, 'D0': D0, 'j': j_inv } break if found: break if found: break if found: break
if found is None: print("[-] Failed!"); sys.exit(1)
E = found['E'] E_prime_factors = found['factors'] p = found['p'] trace_val = found['t'] D0_used = found['D0'] j_used = found['j']
print(f"\n[+] SUCCESS after {E_count} E candidates ({time.time()-t0:.1f}s)") print(f" E = {E} ({Integer(E).nbits()} bits)") print(f" p1={E_prime_factors[0]}, p2={E_prime_factors[1]}, p3={E_prime_factors[2]}") print(f" p = {p}, trace = {trace_val}, D0 = {D0_used}, j = {j_used}")
all_small_factors = set() for pp in E_prime_factors: for f, e in factor(pp - 1): all_small_factors.add((int(f), e)) print(f" Max prime in p_i-1: {max(f for f,e in all_small_factors)}")
print("\n[*] Constructing curve via CM") t3 = time.time()
Fp = GF(p) curve = None
j_fp = Fp(j_used) if j_used == 0: g = Fp.multiplicative_generator() cands = [EllipticCurve(Fp, [0, g^i]) for i in range(6)] elif j_used == 1728: g = Fp.multiplicative_generator() cands = [EllipticCurve(Fp, [g^i, 0]) for i in range(4)] else: k = j_fp / (Fp(1728) - j_fp) a4, a6 = Fp(3)*k, Fp(2)*k C = EllipticCurve(Fp, [a4, a6]) cands = [C, C.quadratic_twist()]
for C in cands: try: if C.order() == E: curve = C print(f"[+] CM succeeded! ({time.time()-t3:.1f}s)") break except: continue
if curve is None: print("[-] CM failed to produce correct order!"); sys.exit(1)
a_int = int(curve.a4()) b_int = int(curve.a6()) print(f" a = {a_int}, b = {b_int}")
print("\n[*] Finding generator") G = None for _ in range(500): P = curve.random_point() if P != curve(0) and int(E) * P == curve(0): G = P; break if G is None: print("[-] No generator!"); sys.exit(1)
gx, gy = int(G[0]), int(G[1]) print(f"[+] G = ({gx}, {gy})")
print("\n[*] Connecting to remote...") t5 = time.time()
HOST = "155.248.210.243" PORT = 42123
io = remote(HOST, PORT)
io.sendlineafter(b'a:', str(a_int).encode()) io.sendlineafter(b'b:', str(b_int).encode()) io.sendlineafter(b'p:', str(int(p)).encode()) io.sendlineafter(b'E', str(int(E)).encode()) io.sendlineafter(b'g.x:', str(gx).encode()) io.sendlineafter(b'g.y:', str(gy).encode())
resp = io.recvall(timeout=60).decode().strip() io.close() print(f" Response: {resp}") print(f" ({time.time()-t5:.1f}s)")
tuples = re.findall(r'\((\d+),\s*(\d+)\)', resp) if len(tuples) >= 2: P1x, P1y = int(tuples[0][0]), int(tuples[0][1]) P2x, P2y = int(tuples[1][0]), int(tuples[1][1]) else: print(f"[-] Failed to parse points! Response: {repr(resp)}") sys.exit(1)
print(f"[+] P1 = ({P1x}, {P1y})") print(f"[+] P2 = ({P2x}, {P2y})")
print("\n[*] Pohlig-Hellman ECDLP") t6 = time.time()
P1 = curve(P1x, P1y) P2 = curve(P2x, P2y)
def bsgs_ecdlp(target, gen, q, curve_zero): """Baby-step Giant-step for ECDLP in subgroup of order q. Stores (x,y) tuples as keys for exact matching.""" q = int(q) m = int(q**0.5) + 1
print(f" Baby steps (m={m})...", end="", flush=True) t_bs = time.time() baby = {} P = curve_zero for j in range(m): if P == curve_zero: baby['inf'] = j else: baby[(int(P[0]), int(P[1]))] = j P = P + gen print(f" done ({time.time()-t_bs:.1f}s)", flush=True)
print(f" Giant steps...", end="", flush=True) t_gs = time.time() giant_step = Integer(-m) * gen
P = target for i in range(m): if P == curve_zero: key = 'inf' else: key = (int(P[0]), int(P[1])) if key in baby: print(f" found at i={i} ({time.time()-t_gs:.1f}s)", flush=True) return (baby[key] + i * m) % q P = P + giant_step
raise ValueError(f"BSGS failed for q={q}")
def pohlig_hellman(target, gen, order, factors): residues, moduli = [], [] curve_zero = curve(0) for q in factors: cofactor = order // q G_sub = Integer(cofactor) * gen T_sub = Integer(cofactor) * target if G_sub == curve_zero: residues.append(Integer(0)); moduli.append(Integer(q)); continue if T_sub == curve_zero: residues.append(Integer(0)); moduli.append(Integer(q)); continue t_q = time.time() k_q = bsgs_ecdlp(T_sub, G_sub, q, curve_zero) print(f" q={q}: k={k_q} ({time.time()-t_q:.1f}s)") residues.append(Integer(k_q)); moduli.append(Integer(q)) return CRT_list(residues, moduli)
print(" Solving f1...") f1 = pohlig_hellman(P1, G, Integer(E), [Integer(x) for x in E_prime_factors]) print(f" f1 = {f1}") print(" Solving f2...") f2 = pohlig_hellman(P2, G, Integer(E), [Integer(x) for x in E_prime_factors]) print(f" f2 = {f2}")
assert Integer(f1) * G == P1, "f1 check failed!" assert Integer(f2) * G == P2, "f2 check failed!" print(f"[+] Verified! ({time.time()-t6:.1f}s)")
print("\n[*] Recovering flag (brute-forcing k offsets)...") max_18 = (1 << 144) - 1 best_flag = None
for k1 in range(int(max_18 // int(E)) + 1): real_f1 = int(f1) + k1 * int(E) if real_f1 > max_18: break b1 = real_f1.to_bytes(18, 'big') if not all(32 <= c < 127 or c == 0 for c in b1): continue for k2 in range(int(max_18 // int(E)) + 1): real_f2 = int(f2) + k2 * int(E) if real_f2 > max_18: break b2 = real_f2.to_bytes(18, 'big') content = b1 + b2 text = content.replace(b'\x00', b'') if all(32 <= c < 127 for c in text) and len(text) >= 20: flag = b'ictf{' + text + b'}' print(f" k1={k1}, k2={k2}: {flag.decode()}") if best_flag is None: best_flag = flag
if best_flag: print(f"\n{'='*70}") print(f"FLAG: {best_flag.decode()}") print(f"{'='*70}") with open('flag.txt', 'wb') as ff: ff.write(best_flag) else: print("[-] Could not find printable flag!") flag_part1 = int(f1).to_bytes(18, 'big') flag_part2 = int(f2).to_bytes(18, 'big') flag = b'ictf{' + flag_part1 + flag_part2 + b'}' print(f"FLAG (hex): {flag.hex()}") with open('flag.txt', 'wb') as ff: ff.write(flag)
print(f"[+] Done! Total time: {time.time()-t0:.1f}s")
|