Skip to content

Instantly share code, notes, and snippets.

@0xTowel
Last active August 1, 2023 16:49
Show Gist options
  • Save 0xTowel/b4e7233fc86d8bb49698e4f1318a5a73 to your computer and use it in GitHub Desktop.
Save 0xTowel/b4e7233fc86d8bb49698e4f1318a5a73 to your computer and use it in GitHub Desktop.
Simple Baby-Step-Giant-Step implementation in Python3 for finding discrete logs with a prime modulus
#!/usr/bin/env python3
# -*- coding:utf-8 -*-
# Towel 2017
from math import ceil, sqrt
def bsgs(g, h, p):
'''
Solve for x in h = g^x mod p given a prime p.
If p is not prime, you shouldn't use BSGS anyway.
'''
N = ceil(sqrt(p - 1)) # phi(p) is p-1 if p is prime
# Store hashmap of g^{1...m} (mod p). Baby step.
tbl = {pow(g, i, p): i for i in range(N)}
# Precompute via Fermat's Little Theorem
c = pow(g, N * (p - 2), p)
# Search for an equivalence in the table. Giant step.
for j in range(N):
y = (h * pow(c, j, p)) % p
if y in tbl:
return j * N + tbl[y]
# Solution not found
return None
print(bsgs(7894352216, 355407489, 604604729))
@PiepsC
Copy link

PiepsC commented Jun 11, 2020

I'm a little lost on what you are computing for c.

Edit: nevermind. You're using Fermat's on the order of p. Ie inverse N.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment