forked from pablocelayes/rsa-wiener-attack
-
Notifications
You must be signed in to change notification settings - Fork 0
/
RSAwienerHacker.py
64 lines (45 loc) · 1.47 KB
/
RSAwienerHacker.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
'''
Created on Dec 14, 2011
@author: pablocelayes
'''
import ContinuedFractions, Arithmetic, RSAvulnerableKeyGenerator
def hack_RSA(e,n):
'''
Finds d knowing (e,n)
applying the Wiener continued fraction attack
'''
frac = ContinuedFractions.rational_to_contfrac(e, n)
convergents = ContinuedFractions.convergents_from_contfrac(frac)
for (k,d) in convergents:
#check if d is actually the key
if k!=0 and (e*d-1)%k == 0:
phi = (e*d-1)//k
s = n - phi + 1
# check if the equation x^2 - s*x + n = 0
# has integer roots
discr = s*s - 4*n
if(discr>=0):
t = Arithmetic.is_perfect_square(discr)
if t!=-1 and (s+t)%2==0:
print("Hacked!")
return d
# TEST functions
def test_hack_RSA():
print("Testing Wiener Attack")
times = 5
while(times>0):
e,n,d = RSAvulnerableKeyGenerator.generateKeys(1024)
print("(e,n) is (", e, ", ", n, ")")
print("d = ", d)
hacked_d = hack_RSA(e, n)
if d == hacked_d:
print("Hack WORKED!")
else:
print("Hack FAILED")
print("d = ", d, ", hacked_d = ", hacked_d)
print("-------------------------")
times -= 1
if __name__ == "__main__":
#test_is_perfect_square()
#print("-------------------------")
test_hack_RSA()