Path: blob/master/attacks/factorization/implicit.py
2589 views
import os1import sys2from math import gcd34from sage.all import ZZ5from sage.all import matrix67path = os.path.dirname(os.path.dirname(os.path.dirname(os.path.realpath(os.path.abspath(__file__)))))8if sys.path[1] != path:9sys.path.insert(1, path)1011from shared.lattice import shortest_vectors121314def _recover_factors(L, N):15for v in shortest_vectors(L):16factors = []17for i, Ni in enumerate(N):18qi = gcd(v[i], Ni)19if 1 < qi < Ni and Ni % qi == 0:20factors.append((Ni // qi, qi))2122if len(factors) == len(N):23return factors242526def factorize_msb(N, n, t):27"""28Factorizes the moduli when some most significant bits are equal among multiples of a prime factor.29More information: Nitaj A., Ariffin MRK., "Implicit factorization of unbalanced RSA moduli" (Section 4)30:param N: the moduli31:param n: the bit length of the moduli32:param t: the number of shared most significant bits33:return: a list containing a tuple of the factors of each modulus, or None if the factors were not found34"""35L = matrix(ZZ, len(N), len(N))36L[0, 0] = 2 ** (n - t)37for i in range(1, len(N)):38L[0, i] = N[i]3940for i in range(1, len(N)):41L[i, i] = -N[0]4243return _recover_factors(L, N)444546def factorize_lsb(N, n, t):47"""48Factorizes the moduli when some least significant bits are equal among multiples of a prime factor.49More information: Nitaj A., Ariffin MRK., "Implicit factorization of unbalanced RSA moduli" (Section 6)50:param N: the moduli51:param n: the bit length of the moduli52:param t: the number of shared least significant bits53:return: a list containing a tuple of the factors of each modulus, or None if the factors were not found54"""55L = matrix(ZZ, len(N), len(N))56L[0, 0] = 157for i in range(1, len(N)):58L[0, i] = N[i] * pow(N[0], -1, 2 ** t) % (2 ** t)5960for i in range(1, len(N)):61L[i, i] = -2 ** t6263return _recover_factors(L, N)646566