Path: blob/master/RSA-encryption/Attack-Hastad-Broadcast/hastad_unpadded.py
851 views
#!/usr/bin/env python2.71from Crypto.Util.number import GCD, bytes_to_long, long_to_bytes2import gmpy234def crt(list_a, list_m):5"""6Reference: https://crypto.stanford.edu/pbc/notes/numbertheory/crt.html7Returns the output after computing Chinese Remainder Theorem on89x = a_1 mod m_110x = a_2 mod m_211...12x = a_n mod m_n1314input parameter list_a = [a_1, a_2, ..., a_n]15input parameter list_m = [m_1, m_2, ..., m_n]1617Returns -1 if the operation is unsuccessful due to some exceptions18"""19try:20assert len(list_a) == len(list_m)21except:22print "[+] Length of list_a should be equal to length of list_m"23return -124for i in range(len(list_m)):25for j in range(len(list_m)):26if GCD(list_m[i], list_m[j])!= 1 and i!=j:27print "[+] Moduli should be pairwise co-prime"28return -129M = 130for i in list_m:31M *= i32list_b = [M/i for i in list_m]33assert len(list_b) == len(list_m)34try:35list_b_inv = [int(gmpy2.invert(list_b[i], list_m[i])) for i in range(len(list_m))]36except:37print "[+] Encountered an unusual error while calculating inverse using gmpy2.invert()"38return -139x = 040for i in range(len(list_m)):41x += list_a[i]*list_b[i]*list_b_inv[i]42return x % M434445def test_crt():46"""47Checking the validity and consistency of CRT function48"""49list_a = [[2, 3], [1, 2, 3, 4], [6, 4]]50list_m = [[5, 7], [5, 7, 9, 11], [7, 8]]51soln_list = [17, 1731, 20]52try:53for i in range(len(list_a)):54assert crt(list_a[i], list_m[i]) == soln_list[i]55except:56print "[+] CRT function broken. Check the function again!"575859def hastad_unpadded(ct_list, mod_list, e):60"""61Implementing Hastad's Broadcast Attack62"""63m_expo = crt(ct_list, mod_list)64if m_expo != -1:65eth_root = gmpy2.iroot(m_expo, e)66if eth_root[1] == False:67print "[+] Cannot calculate e'th root!"68return -169elif eth_root[1] == True:70return long_to_bytes(eth_root)71else:72print "[+] Cannot calculate CRT"73return -17475test_crt()767778