Path: blob/master/Discrete-Logarithm-Problem/Algo-Pohlig-Hellman/pohlig_hellman.py
1392 views
from Crypto.Util.number import *12def crt(list_a, list_m):3try:4assert len(list_a) == len(list_m)5except:6print "[+] Length of list_a should be equal to length of list_m"7return -18for i in range(len(list_m)):9for j in range(len(list_m)):10if GCD(list_m[i], list_m[j])!= 1 and i!=j:11print "[+] Moduli should be pairwise co-prime"12return -113M = 114for i in list_m:15M *= i16list_b = [M/i for i in list_m]17assert len(list_b) == len(list_m)18try:19assert [GCD(list_b[i], list_m[i]) == 1 for i in range(len(list_m))]20list_b_inv = [int(inverse(list_b[i], list_m[i])) for i in range(len(list_m))]21except:22print "[+] Encountered an unusual error while calculating inverse using gmpy2.invert()"23return -124x = 025for i in range(len(list_m)):26x += list_a[i]*list_b[i]*list_b_inv[i]27return x % M2829def brute_dlp(g, y, p):30mod_size = len(bin(p-1)[2:])31sol = pow(g, 2, p)32if y == 1:33return 034if y == g:35return 136if sol == y:37return 238i = 339while i <= p-1:40sol = sol*g % p41if sol == y:42return i43i += 144return None4546def pohlig_hellman_pp(g, y, p, q, e):47try:48# Assume q is a factor of p-149assert (p-1) % q == 050except:51print "[-] Error! q**e not a factor of p-1"52return -15354# a = a_0*(q**0) + a_1*(q**1) + a_2*(q**2) + ... + a_(e-1)*(q**(e-1)) + s*(q**e)55# where a_0, a_1, a_2, ..., a_(e-1) belong to {0,1,...,q-1} and s is some integer56a = 05758b_j = y59alpha = pow(g, (p-1)/q, p)60for j in range(e):61y_i = pow(b_j, (p-1)/(q**(j+1)), p)62a_j = brute_dlp(alpha, y_i, p)63assert a_j >= 0 and a_j <= q-164a += a_j*(q**j)6566multiplier = pow(g, a_j*(q**j), p)67assert GCD(multiplier, p) == 168b_j = (b_j * inverse(multiplier, p)) % p69return a7071def pohlig_hellman(g, y, p, list_q, list_e):72x_list = [pohlig_hellman_pp(g, y, p, list_q[i], list_e[i]) for i in range(len(list_q))]73mod_list = [list_q[i]**list_e[i] for i in range(len(list_q))]74return crt(x_list, mod_list)7576if __name__ == "__main__":77p = 0xfffffed83c1778print pohlig_hellman(5, 230152795807443, p, [2, 3, 7, 13, 47, 103, 107, 151], [1, 2, 1, 4, 1, 1, 1, 1])798081