Path: blob/master/attacks/factorization/unbalanced.py
2589 views
import logging1import os2import sys34from sage.all import ZZ56path = os.path.dirname(os.path.dirname(os.path.dirname(os.path.realpath(os.path.abspath(__file__)))))7if sys.path[1] != path:8sys.path.insert(1, path)910from shared.small_roots import herrmann_may111213def factorize(N, partial_p, Q, m=1, t=None, check_bounds=True):14"""15Recovers the prime factors from a modulus if the modulus is unbalanced and bits are known.16More information: Brier E. et al., "Factoring Unbalanced Moduli with Known Bits" (Section 4)17:param N: the modulus: N = p * q > q ** 318:param partial_p: the partial prime factor p (PartialInteger)19:param Q: the bit length of q20:param m: the m value to use for the small roots method (default: 1)21:param t: the t value to use for the small roots method (default: automatically computed using m)22:param check_bounds: perform bounds check (default: True)23:return: a tuple containing the prime factors, or None if the factors could not be found24"""25W = partial_p.get_unknown_lsb()26assert W > 0, "Number of unknown lsb must be greater than 0 (try adding a dummy unknown bit)."27v, L = partial_p.get_known_middle()28assert not check_bounds or 3 * L ** 2 + (4 * W - 6 * Q) * L + 3 * Q ** 2 - 8 * Q * W > 0, f"Bounds check failed ({3 * L ** 2 + (4 * W - 6 * Q) * L + 3 * Q ** 2 - 8 * Q * W} > 0)."29delta = Q / (W + L)3031x, y = ZZ["x", "y"].gens()32a = v * 2 ** W33b = N % (2 ** (W + L))34f = x * (a + y) - b35X = 2 ** Q36Y = 2 ** W37t = int((1 - 2 * delta) * m) if t is None else t38logging.info(f"Trying {m = }, {t = }...")39for x0, y0 in herrmann_may.modular_bivariate(f, 2 ** (W + L), m, t, X, Y):40q = x041if q != 0 and N % q == 0:42return N // q, q4344return None454647