Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
jvdsn
GitHub Repository: jvdsn/crypto-attacks
Path: blob/master/attacks/rsa/wiener_attack.py
2589 views
1
import os
2
import sys
3
4
from sage.all import ZZ
5
from sage.all import continued_fraction
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 attacks.factorization import known_phi
12
13
14
def attack(N, e):
15
"""
16
Recovers the prime factors of a modulus and the private exponent if the private exponent is too small.
17
:param N: the modulus
18
:param e: the public exponent
19
:return: a tuple containing the prime factors and the private exponent, or None if the private exponent was not found
20
"""
21
convergents = continued_fraction(ZZ(e) / ZZ(N)).convergents()
22
for c in convergents:
23
k = c.numerator()
24
d = c.denominator()
25
if pow(pow(2, e, N), d, N) != 2:
26
continue
27
28
phi = (e * d - 1) // k
29
factors = known_phi.factorize(N, phi)
30
if factors:
31
return *factors, int(d)
32
33