mpz(n) #初始化一个大整数 mpfr(x) # 初始化一个高精度浮点数x d = invert(e,n) # 求逆元,de = 1 mod n c = powmod(m,e,n) # 幂取模,结果是 c = m^e mod n is_prime(n) #素性检测 gcd(a,b) #欧几里得算法,最大公约数 gcdext(a,b) #扩展欧几里得算法 iroot(x,n) #x开n次根
import os from re import findall from subprocess import check_output
defflatter(M): # compile https://github.com/keeganryan/flatter and put it in $PATH z = "[[" + "]\n[".join(" ".join(map(str, row)) for row in M) + "]]" ret = check_output(["flatter"], input=z.encode()) return matrix(M.nrows(), M.ncols(), map(int, findall(b"-?\\d+", ret))) L = flatter(L) # L = L.LLL()
N = 7803960993055714764790127684076211863657988334421459147942569078964485679825779792612991909294331632362413082874625938556130231837335088680459104018893959 p_lsb = 779432292600303509528505569280402295375268661469 num_lsbs = 160
# x represents the unknown lsbs x = var('x') # f(x) == 0 (mod p) when x is the 96 most significant bits of p f = 2**160 * x + p_lsb
# Only one polynomial in our system relations = [f] # We give lower and upper bounds of x bounds = {x: (0, 2**96)} roots = cuso.find_small_roots( relations, bounds, modulus = "p", modulus_multiple = N, modulus_lower_bound = 2**255, ) assertlen(roots) > 0 p = roots[0]["p"] assert N % p == 0 print(f"Recovered factor p = {p}")
N = 7803960993055714764790127684076211863657988334421459147942569078964485679825779792612991909294331632362413082874625938556130231837335088680459104018893959 e = 7338455574804691890149651420174638680950093405994546367015621732049630822037090156191940077914112346956150999747345628657616947167917355899104335150736479 priv_exp_len = 136
p, q, k = var('p, q, k') # By the RSA equation, # e * d = 1 + k*(p - 1)*(q - 1) # N = p * q # where d, k, p, and q are unknown. # The first relation is modulo e; # the second doesn't have a modulus. phi = (p - 1) * (q - 1) relations = [ 0 == 1 + k * phi, N == p * q, ] moduli = [ e, None, ]
# We give lower and upper bounds of p, q, and k. bounds = { p: (2**255, 2**256), q: (2**255, 2**256), k: (0, 2**priv_exp_len), } roots = cuso.find_small_roots( relations, bounds, modulus=moduli, ) assertlen(roots) > 0 phi = phi.subs(roots[0]) d = int(inverse_mod(e, phi)) print(f"Recovered small exponent d = {d}")