Path: blob/master/attacks/factorization/base_conversion.py
2589 views
import logging12from sage.all import ZZ345def factorize(N, coefficient_threshold=32):6"""7Recovers the prime factors from a modulus by converting it to different bases.8:param N: the modulus9:param coefficient_threshold: the threshold of coefficients below which we will try to factor a base k polynomial10:return: a tuple containing the prime factors11"""12R = ZZ["x"]13base = 214while True:15logging.debug(f"Trying {base = }...")16poly = R(ZZ(N).digits(base))17logging.debug(f"Got {len(poly.coefficients())} coefficients")18if len(poly.coefficients()) < coefficient_threshold:19facs = poly.factor()20return tuple(map(lambda f: int(f[0](base)), facs))2122base += 1232425def factorize_base_2x(N):26"""27Recovers the prime factors from a modulus by converting it to different bases of the form 2^x.28:param N: the modulus29:return: a tuple containing the prime factors30"""31R = ZZ["x"]32base = 233while True:34logging.debug(f"Trying {base = }...")35poly = R(ZZ(N).digits(base))36facs = poly.factor()37if len(facs) > 1:38return tuple(map(lambda f: int(f[0](base)), facs))3940base *= 2414243