Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
ashutosh1206
GitHub Repository: ashutosh1206/crypton
Path: blob/master/Discrete-Logarithm-Problem/Algo-Pohlig-Hellman/ph_orderpp.py
1392 views
1
from Crypto.Util.number import *
2
3
def brute_dlp(g, y, p):
4
mod_size = len(bin(p-1)[2:])
5
sol = pow(g, 2, p)
6
if y == 1:
7
return 0
8
if y == g:
9
return 1
10
if sol == y:
11
return y
12
i = 3
13
while i <= p-1:
14
sol = sol*g % p
15
if sol == y:
16
return i
17
i += 1
18
return None
19
20
def pohlig_hellman_pp(g, y, p, q, e):
21
"""
22
Reference: http://anh.cs.luc.edu/331/notes/PohligHellmanp_k2p.pdf
23
24
Computes `x` = a mod (p-1) for the DLP g**x % p == y
25
in the Group G = {0, 1, 2, ..., p-1}
26
given that order `n` = p-1 is a power of a small prime,
27
ie. n = p-1 = q**e, where q is a small prime
28
29
:parameters:
30
g : int/long
31
Generator of the group
32
y : int/long
33
Result of g**x % p
34
p : int/long
35
Group over which DLP is generated. Commonly p is a prime number
36
e : int/long
37
Exponent of 2 in the group order: n = p-1 = q**e
38
"""
39
40
try:
41
assert p-1 == q**e
42
# Assume q is a factor of p-1
43
assert (p-1) % q == 0
44
except:
45
print "[-] Error! q**e not a factor of p-1"
46
return -1
47
48
# a = a_0*(q**0) + a_1*(q**1) + a_2*(q**2) + ... + a_(e-1)*(q**(e-1)) + s*(q**e)
49
# where a_0, a_1, a_2, ..., a_(e-1) belong to {0,1,...,q-1} and s is some integer
50
a = 0
51
52
b_j = y
53
alpha = pow(g, (p-1)/q, p)
54
for j in range(e):
55
y_i = pow(b_j, (p-1)/(q**(j+1)), p)
56
a_j = brute_dlp(alpha, y_i, p)
57
assert a_j >= 0 and a_j <= q-1
58
a += a_j*(q**j)
59
60
multiplier = pow(g, a_j*(q**j), p)
61
assert GCD(multiplier, p) == 1
62
b_j = (b_j * inverse(multiplier, p)) % p
63
return a
64
65
if __name__ == "__main__":
66
assert pow(3, pohlig_hellman_pp(3, 188, 257, 2, 8), 257) == 188
67
68