Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
ashutosh1206
GitHub Repository: ashutosh1206/crypton
Path: blob/master/Discrete-Logarithm-Problem/Algo-Baby-Step-Giant-Step/bsgs.py
1402 views
1
from sage.all import *
2
3
def bsgs(g, y, p):
4
"""
5
Reference:
6
7
To solve DLP: y = g^x % p and get the value of x.
8
We use the property that x = i*m + j, where m = ceil(sqrt(n))
9
10
:parameters:
11
g : int/long
12
Generator of the group
13
y : int/long
14
Result of g**x % p
15
p : int/long
16
Group over which DLP is generated. Commonly p is a prime number
17
18
:variables:
19
m : int/long
20
Upper limit of baby steps / giant steps
21
x_poss : int/long
22
Values calculated in each giant step
23
c : int/long
24
Giant Step pre-computation: c = g^(-m) % p
25
i, j : int/long
26
Giant Step, Baby Step variables
27
lookup_table: dictionary
28
Dictionary storing all the values computed in the baby step
29
"""
30
mod_size = len(bin(p-1)[2:])
31
32
print "[+] Using BSGS algorithm to solve DLP"
33
print "[+] Modulus size: " + str(mod_size) + ". Warning! BSGS not space efficient\n"
34
35
m = ceil(sqrt(p-1))
36
# Baby Step
37
lookup_table = {pow(g, j, p): j for j in range(m)}
38
# Giant Step pre-computation
39
c = pow(g, m*(p-2), p)
40
# Giant Steps
41
for i in range(m):
42
temp = (y*pow(c, i, p)) % p
43
if temp in lookup_table:
44
# x found
45
return i*m + lookup_table[temp]
46
return None
47
48
49
if __name__ == "__main__":
50
try:
51
assert pow(2, bsgs(2, 4178319614, 6971096459), 6971096459) == 4178319614
52
assert pow(3, bsgs(3, 362073897, 2500000001), 2500000001) == 362073897
53
except:
54
print "[+] Function inconsistent and incorrect, check the implementation"
55
56