Advertisement
CSenshi

Cryptography - HW3.1 (dlog.py)

Jan 9th, 2020
401
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.89 KB | None | 0 0
  1. import math
  2.  
  3. # Find x such that g^x = h (mod p)
  4. # 0 <= x <= max_x
  5. def discrete_log(g, h, p, max_x):
  6.     # let B be maximum range to iterate over (2^20)
  7.     B = int(math.sqrt(max_x))
  8.  
  9.     # Equation to solve: h/(g^x1) = (g^B)^x0
  10.  
  11.     ''' Iterate Over Left Part of Equation [h/(g^x1)] '''
  12.     # table to save left part equation solutions
  13.     hash_table = {}
  14.     # g^(-1) = g^(p-2)
  15.     g_inv = pow(g, p - 2, p)
  16.     h_g_x1 = h
  17.     # Iterate and fill in hash table
  18.     for x1 in range(B):
  19.         # fill hash table
  20.         hash_table[h_g_x1] = x1
  21.         # h * ((g^-1) ^ x1)
  22.         h_g_x1 *= g_inv
  23.         h_g_x1 %= p
  24.  
  25.     ''' Iterate Over Right Part of Equation [(g^B)^x0] '''
  26.     # g^B
  27.     g_B = pow(g, B, p)
  28.     # Iterate to find such x0 that (g^b)^x0 is in our hash table
  29.     g_B_x0 = 1
  30.     for x0 in range(B):
  31.         # if hash table contains given number then we have foun solution
  32.         if g_B_x0 in hash_table:
  33.             x1 = hash_table[g_B_x0]
  34.             return x0 * B + x1
  35.         # (g^B)^x0
  36.         g_B_x0 = (g_B_x0*g_B) % p
  37.  
  38.  
  39. def main():
  40.     p = 13407807929942597099574024998205846127479365820592393377723561443721764030073546976801874298166903427690031858186486050853753882811946569946433649006084171
  41.     g = 11717829880366207009516117596335367088558084999998952205599979459063929499736583746670572176471460312928594829675428279466566527115212748467589894601965568
  42.     h = 3239475104050450443565264378728065788649097520952449527834792452971981976143292558073856937958553180532878928001494706097394108577585732452307673444020333
  43.     max_x = 1 << 40  # 2^40
  44.     x = discrete_log(g, h, p, max_x)
  45.  
  46.     # check if discrete logarithm is correct
  47.     ans = pow(g, x, p)
  48.     if (ans == h):
  49.         print("Discrete Logarithm is correct!")
  50.         print("Result : x={}".format(x))
  51.     else:
  52.         print("Discrete Logarithm is incorrect!")
  53.  
  54.  
  55. if __name__ == '__main__':
  56.     main()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement