Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
ashutosh1206
GitHub Repository: ashutosh1206/crypton
Path: blob/master/Discrete-Logarithm-Problem/Algo-Pohlig-Hellman/pohlig_hellman.py
1392 views
1
from Crypto.Util.number import *
2
3
def crt(list_a, list_m):
4
try:
5
assert len(list_a) == len(list_m)
6
except:
7
print "[+] Length of list_a should be equal to length of list_m"
8
return -1
9
for i in range(len(list_m)):
10
for j in range(len(list_m)):
11
if GCD(list_m[i], list_m[j])!= 1 and i!=j:
12
print "[+] Moduli should be pairwise co-prime"
13
return -1
14
M = 1
15
for i in list_m:
16
M *= i
17
list_b = [M/i for i in list_m]
18
assert len(list_b) == len(list_m)
19
try:
20
assert [GCD(list_b[i], list_m[i]) == 1 for i in range(len(list_m))]
21
list_b_inv = [int(inverse(list_b[i], list_m[i])) for i in range(len(list_m))]
22
except:
23
print "[+] Encountered an unusual error while calculating inverse using gmpy2.invert()"
24
return -1
25
x = 0
26
for i in range(len(list_m)):
27
x += list_a[i]*list_b[i]*list_b_inv[i]
28
return x % M
29
30
def brute_dlp(g, y, p):
31
mod_size = len(bin(p-1)[2:])
32
sol = pow(g, 2, p)
33
if y == 1:
34
return 0
35
if y == g:
36
return 1
37
if sol == y:
38
return 2
39
i = 3
40
while i <= p-1:
41
sol = sol*g % p
42
if sol == y:
43
return i
44
i += 1
45
return None
46
47
def pohlig_hellman_pp(g, y, p, q, e):
48
try:
49
# Assume q is a factor of p-1
50
assert (p-1) % q == 0
51
except:
52
print "[-] Error! q**e not a factor of p-1"
53
return -1
54
55
# a = a_0*(q**0) + a_1*(q**1) + a_2*(q**2) + ... + a_(e-1)*(q**(e-1)) + s*(q**e)
56
# where a_0, a_1, a_2, ..., a_(e-1) belong to {0,1,...,q-1} and s is some integer
57
a = 0
58
59
b_j = y
60
alpha = pow(g, (p-1)/q, p)
61
for j in range(e):
62
y_i = pow(b_j, (p-1)/(q**(j+1)), p)
63
a_j = brute_dlp(alpha, y_i, p)
64
assert a_j >= 0 and a_j <= q-1
65
a += a_j*(q**j)
66
67
multiplier = pow(g, a_j*(q**j), p)
68
assert GCD(multiplier, p) == 1
69
b_j = (b_j * inverse(multiplier, p)) % p
70
return a
71
72
def pohlig_hellman(g, y, p, list_q, list_e):
73
x_list = [pohlig_hellman_pp(g, y, p, list_q[i], list_e[i]) for i in range(len(list_q))]
74
mod_list = [list_q[i]**list_e[i] for i in range(len(list_q))]
75
return crt(x_list, mod_list)
76
77
if __name__ == "__main__":
78
p = 0xfffffed83c17
79
print pohlig_hellman(5, 230152795807443, p, [2, 3, 7, 13, 47, 103, 107, 151], [1, 2, 1, 4, 1, 1, 1, 1])
80
81