Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
jvdsn
GitHub Repository: jvdsn/crypto-attacks
Path: blob/master/attacks/factorization/base_conversion.py
2589 views
1
import logging
2
3
from sage.all import ZZ
4
5
6
def factorize(N, coefficient_threshold=32):
7
"""
8
Recovers the prime factors from a modulus by converting it to different bases.
9
:param N: the modulus
10
:param coefficient_threshold: the threshold of coefficients below which we will try to factor a base k polynomial
11
:return: a tuple containing the prime factors
12
"""
13
R = ZZ["x"]
14
base = 2
15
while True:
16
logging.debug(f"Trying {base = }...")
17
poly = R(ZZ(N).digits(base))
18
logging.debug(f"Got {len(poly.coefficients())} coefficients")
19
if len(poly.coefficients()) < coefficient_threshold:
20
facs = poly.factor()
21
return tuple(map(lambda f: int(f[0](base)), facs))
22
23
base += 1
24
25
26
def factorize_base_2x(N):
27
"""
28
Recovers the prime factors from a modulus by converting it to different bases of the form 2^x.
29
:param N: the modulus
30
:return: a tuple containing the prime factors
31
"""
32
R = ZZ["x"]
33
base = 2
34
while True:
35
logging.debug(f"Trying {base = }...")
36
poly = R(ZZ(N).digits(base))
37
facs = poly.factor()
38
if len(facs) > 1:
39
return tuple(map(lambda f: int(f[0](base)), facs))
40
41
base *= 2
42
43