|
| 1 | +from math import ceil, sqrt |
| 2 | + |
| 3 | + |
| 4 | +# Baby-Step-Giant-Step implementation by 0xTowel |
| 5 | +# https://gist.github.com/0xTowel/b4e7233fc86d8bb49698e4f1318a5a73 |
| 6 | +def bsgs(g, h, p): |
| 7 | + ''' |
| 8 | + Solve for x in h = g^x mod p given a prime p. |
| 9 | + If p is not prime, you shouldn't use BSGS anyway. |
| 10 | + ''' |
| 11 | + N = ceil(sqrt(p - 1)) # phi(p) is p-1 if p is prime |
| 12 | + |
| 13 | + # Store hashmap of g^{1...m} (mod p). Baby step. |
| 14 | + tbl = {pow(g, i, p): i for i in range(N)} |
| 15 | + |
| 16 | + # Precompute via Fermat's Little Theorem |
| 17 | + c = pow(g, N * (p - 2), p) |
| 18 | + |
| 19 | + # Search for an equivalence in the table. Giant step. |
| 20 | + for j in range(N): |
| 21 | + y = (h * pow(c, j, p)) % p |
| 22 | + if y in tbl: |
| 23 | + return j * N + tbl[y] |
| 24 | + |
| 25 | + # Solution not found |
| 26 | + return None |
| 27 | + |
| 28 | + |
| 29 | +def main(): |
| 30 | + mod = 20201227 |
| 31 | + card_pub = 3418282 |
| 32 | + door_pub = 8719412 |
| 33 | + |
| 34 | + card_loop = bsgs(7, card_pub, mod) |
| 35 | + door_loop = bsgs(7, door_pub, mod) |
| 36 | + print(card_loop) |
| 37 | + print(door_loop) |
| 38 | + |
| 39 | + # Check if the computation was correct |
| 40 | + print(pow(7, card_loop, mod)) |
| 41 | + print(pow(7, door_loop, mod)) |
| 42 | + |
| 43 | + # This is the answer |
| 44 | + print(pow(door_pub, card_loop, mod)) |
| 45 | + print(pow(card_pub, door_loop, mod)) |
| 46 | + |
| 47 | + |
| 48 | +main() |
0 commit comments