Path: blob/master/Discrete-Logarithm-Problem/Algo-Baby-Step-Giant-Step/bsgs.py
1402 views
from sage.all import *12def bsgs(g, y, p):3"""4Reference:56To solve DLP: y = g^x % p and get the value of x.7We use the property that x = i*m + j, where m = ceil(sqrt(n))89:parameters:10g : int/long11Generator of the group12y : int/long13Result of g**x % p14p : int/long15Group over which DLP is generated. Commonly p is a prime number1617:variables:18m : int/long19Upper limit of baby steps / giant steps20x_poss : int/long21Values calculated in each giant step22c : int/long23Giant Step pre-computation: c = g^(-m) % p24i, j : int/long25Giant Step, Baby Step variables26lookup_table: dictionary27Dictionary storing all the values computed in the baby step28"""29mod_size = len(bin(p-1)[2:])3031print "[+] Using BSGS algorithm to solve DLP"32print "[+] Modulus size: " + str(mod_size) + ". Warning! BSGS not space efficient\n"3334m = ceil(sqrt(p-1))35# Baby Step36lookup_table = {pow(g, j, p): j for j in range(m)}37# Giant Step pre-computation38c = pow(g, m*(p-2), p)39# Giant Steps40for i in range(m):41temp = (y*pow(c, i, p)) % p42if temp in lookup_table:43# x found44return i*m + lookup_table[temp]45return None464748if __name__ == "__main__":49try:50assert pow(2, bsgs(2, 4178319614, 6971096459), 6971096459) == 417831961451assert pow(3, bsgs(3, 362073897, 2500000001), 2500000001) == 36207389752except:53print "[+] Function inconsistent and incorrect, check the implementation"545556