Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
jvdsn
GitHub Repository: jvdsn/crypto-attacks
Path: blob/master/attacks/factorization/fermat.py
2589 views
1
import os
2
import sys
3
4
from math import isqrt
5
6
path = os.path.dirname(os.path.dirname(os.path.dirname(os.path.realpath(os.path.abspath(__file__)))))
7
if sys.path[1] != path:
8
sys.path.insert(1, path)
9
10
from shared import is_square
11
12
13
def factorize(N):
14
"""
15
Recovers the prime factors from a modulus using Fermat's factorization method.
16
:param N: the modulus
17
:return: a tuple containing the prime factors, or None if the factors were not found
18
"""
19
a = isqrt(N)
20
b = a * a - N
21
while b < 0 or not is_square(b):
22
a += 1
23
b = a * a - N
24
25
p = a - isqrt(b)
26
q = N // p
27
return p, q if p * q == N else None
28
29