Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
jvdsn
GitHub Repository: jvdsn/crypto-attacks
Path: blob/master/attacks/factorization/implicit.py
2589 views
1
import os
2
import sys
3
from math import gcd
4
5
from sage.all import ZZ
6
from sage.all import matrix
7
8
path = os.path.dirname(os.path.dirname(os.path.dirname(os.path.realpath(os.path.abspath(__file__)))))
9
if sys.path[1] != path:
10
sys.path.insert(1, path)
11
12
from shared.lattice import shortest_vectors
13
14
15
def _recover_factors(L, N):
16
for v in shortest_vectors(L):
17
factors = []
18
for i, Ni in enumerate(N):
19
qi = gcd(v[i], Ni)
20
if 1 < qi < Ni and Ni % qi == 0:
21
factors.append((Ni // qi, qi))
22
23
if len(factors) == len(N):
24
return factors
25
26
27
def factorize_msb(N, n, t):
28
"""
29
Factorizes the moduli when some most significant bits are equal among multiples of a prime factor.
30
More information: Nitaj A., Ariffin MRK., "Implicit factorization of unbalanced RSA moduli" (Section 4)
31
:param N: the moduli
32
:param n: the bit length of the moduli
33
:param t: the number of shared most significant bits
34
:return: a list containing a tuple of the factors of each modulus, or None if the factors were not found
35
"""
36
L = matrix(ZZ, len(N), len(N))
37
L[0, 0] = 2 ** (n - t)
38
for i in range(1, len(N)):
39
L[0, i] = N[i]
40
41
for i in range(1, len(N)):
42
L[i, i] = -N[0]
43
44
return _recover_factors(L, N)
45
46
47
def factorize_lsb(N, n, t):
48
"""
49
Factorizes the moduli when some least significant bits are equal among multiples of a prime factor.
50
More information: Nitaj A., Ariffin MRK., "Implicit factorization of unbalanced RSA moduli" (Section 6)
51
:param N: the moduli
52
:param n: the bit length of the moduli
53
:param t: the number of shared least significant bits
54
:return: a list containing a tuple of the factors of each modulus, or None if the factors were not found
55
"""
56
L = matrix(ZZ, len(N), len(N))
57
L[0, 0] = 1
58
for i in range(1, len(N)):
59
L[0, i] = N[i] * pow(N[0], -1, 2 ** t) % (2 ** t)
60
61
for i in range(1, len(N)):
62
L[i, i] = -2 ** t
63
64
return _recover_factors(L, N)
65
66