Path: blob/master/Discrete-Logarithm-Problem/Algo-Pohlig-Hellman/ph_orderpp.py
1392 views
from Crypto.Util.number import *12def brute_dlp(g, y, p):3mod_size = len(bin(p-1)[2:])4sol = pow(g, 2, p)5if y == 1:6return 07if y == g:8return 19if sol == y:10return y11i = 312while i <= p-1:13sol = sol*g % p14if sol == y:15return i16i += 117return None1819def pohlig_hellman_pp(g, y, p, q, e):20"""21Reference: http://anh.cs.luc.edu/331/notes/PohligHellmanp_k2p.pdf2223Computes `x` = a mod (p-1) for the DLP g**x % p == y24in the Group G = {0, 1, 2, ..., p-1}25given that order `n` = p-1 is a power of a small prime,26ie. n = p-1 = q**e, where q is a small prime2728:parameters:29g : int/long30Generator of the group31y : int/long32Result of g**x % p33p : int/long34Group over which DLP is generated. Commonly p is a prime number35e : int/long36Exponent of 2 in the group order: n = p-1 = q**e37"""3839try:40assert p-1 == q**e41# Assume q is a factor of p-142assert (p-1) % q == 043except:44print "[-] Error! q**e not a factor of p-1"45return -14647# a = a_0*(q**0) + a_1*(q**1) + a_2*(q**2) + ... + a_(e-1)*(q**(e-1)) + s*(q**e)48# where a_0, a_1, a_2, ..., a_(e-1) belong to {0,1,...,q-1} and s is some integer49a = 05051b_j = y52alpha = pow(g, (p-1)/q, p)53for j in range(e):54y_i = pow(b_j, (p-1)/(q**(j+1)), p)55a_j = brute_dlp(alpha, y_i, p)56assert a_j >= 0 and a_j <= q-157a += a_j*(q**j)5859multiplier = pow(g, a_j*(q**j), p)60assert GCD(multiplier, p) == 161b_j = (b_j * inverse(multiplier, p)) % p62return a6364if __name__ == "__main__":65assert pow(3, pohlig_hellman_pp(3, 188, 257, 2, 8), 257) == 188666768