Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
jvdsn
GitHub Repository: jvdsn/crypto-attacks
Path: blob/master/attacks/factorization/unbalanced.py
2589 views
1
import logging
2
import os
3
import sys
4
5
from sage.all import ZZ
6
7
path = os.path.dirname(os.path.dirname(os.path.dirname(os.path.realpath(os.path.abspath(__file__)))))
8
if sys.path[1] != path:
9
sys.path.insert(1, path)
10
11
from shared.small_roots import herrmann_may
12
13
14
def factorize(N, partial_p, Q, m=1, t=None, check_bounds=True):
15
"""
16
Recovers the prime factors from a modulus if the modulus is unbalanced and bits are known.
17
More information: Brier E. et al., "Factoring Unbalanced Moduli with Known Bits" (Section 4)
18
:param N: the modulus: N = p * q > q ** 3
19
:param partial_p: the partial prime factor p (PartialInteger)
20
:param Q: the bit length of q
21
:param m: the m value to use for the small roots method (default: 1)
22
:param t: the t value to use for the small roots method (default: automatically computed using m)
23
:param check_bounds: perform bounds check (default: True)
24
:return: a tuple containing the prime factors, or None if the factors could not be found
25
"""
26
W = partial_p.get_unknown_lsb()
27
assert W > 0, "Number of unknown lsb must be greater than 0 (try adding a dummy unknown bit)."
28
v, L = partial_p.get_known_middle()
29
assert 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)."
30
delta = Q / (W + L)
31
32
x, y = ZZ["x", "y"].gens()
33
a = v * 2 ** W
34
b = N % (2 ** (W + L))
35
f = x * (a + y) - b
36
X = 2 ** Q
37
Y = 2 ** W
38
t = int((1 - 2 * delta) * m) if t is None else t
39
logging.info(f"Trying {m = }, {t = }...")
40
for x0, y0 in herrmann_may.modular_bivariate(f, 2 ** (W + L), m, t, X, Y):
41
q = x0
42
if q != 0 and N % q == 0:
43
return N // q, q
44
45
return None
46
47