Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
ashutosh1206
GitHub Repository: ashutosh1206/Crypton
Path: blob/master/RSA-encryption/Attack-Hastad-Broadcast/hastad_unpadded.py
851 views
1
#!/usr/bin/env python2.7
2
from Crypto.Util.number import GCD, bytes_to_long, long_to_bytes
3
import gmpy2
4
5
def crt(list_a, list_m):
6
"""
7
Reference: https://crypto.stanford.edu/pbc/notes/numbertheory/crt.html
8
Returns the output after computing Chinese Remainder Theorem on
9
10
x = a_1 mod m_1
11
x = a_2 mod m_2
12
...
13
x = a_n mod m_n
14
15
input parameter list_a = [a_1, a_2, ..., a_n]
16
input parameter list_m = [m_1, m_2, ..., m_n]
17
18
Returns -1 if the operation is unsuccessful due to some exceptions
19
"""
20
try:
21
assert len(list_a) == len(list_m)
22
except:
23
print "[+] Length of list_a should be equal to length of list_m"
24
return -1
25
for i in range(len(list_m)):
26
for j in range(len(list_m)):
27
if GCD(list_m[i], list_m[j])!= 1 and i!=j:
28
print "[+] Moduli should be pairwise co-prime"
29
return -1
30
M = 1
31
for i in list_m:
32
M *= i
33
list_b = [M/i for i in list_m]
34
assert len(list_b) == len(list_m)
35
try:
36
list_b_inv = [int(gmpy2.invert(list_b[i], list_m[i])) for i in range(len(list_m))]
37
except:
38
print "[+] Encountered an unusual error while calculating inverse using gmpy2.invert()"
39
return -1
40
x = 0
41
for i in range(len(list_m)):
42
x += list_a[i]*list_b[i]*list_b_inv[i]
43
return x % M
44
45
46
def test_crt():
47
"""
48
Checking the validity and consistency of CRT function
49
"""
50
list_a = [[2, 3], [1, 2, 3, 4], [6, 4]]
51
list_m = [[5, 7], [5, 7, 9, 11], [7, 8]]
52
soln_list = [17, 1731, 20]
53
try:
54
for i in range(len(list_a)):
55
assert crt(list_a[i], list_m[i]) == soln_list[i]
56
except:
57
print "[+] CRT function broken. Check the function again!"
58
59
60
def hastad_unpadded(ct_list, mod_list, e):
61
"""
62
Implementing Hastad's Broadcast Attack
63
"""
64
m_expo = crt(ct_list, mod_list)
65
if m_expo != -1:
66
eth_root = gmpy2.iroot(m_expo, e)
67
if eth_root[1] == False:
68
print "[+] Cannot calculate e'th root!"
69
return -1
70
elif eth_root[1] == True:
71
return long_to_bytes(eth_root)
72
else:
73
print "[+] Cannot calculate CRT"
74
return -1
75
76
test_crt()
77
78