Baby-Step Giant-Step Algorithm
- •
What it is
- •
A meet-in-the-middle algorithm for solving the discrete logarithm problem within a group (or subgroup) of known order , in time and space — dramatically faster than brute-forcing all possibilities, though still infeasible for the full-size groups real cryptography uses. The trick: write the unknown exponent as for and . Precompute and store every "baby step" for in a lookup table; then take "giant steps" of size starting from , checking at each step whether the current value matches anything in the table — a match at giant-step and table entry means , i.e. .
- •
- •
When to apply
- •
You need to solve a discrete log in a group (or a prime-order subgroup, as the inner step of Pohlig-Hellman) small enough that operations are actually feasible — anywhere from toy sizes up to maybe 40-50 bits by hand, much further with optimized implementations.
- •
- •
Symbols and assumptions
- •
We solve in a subgroup of order . Let and write with . Negative exponents mean group inverses.
- •
- •
Math — step by step
- •
- Rearrange to . The left side takes only possible baby steps.
- •
- Store a dictionary mapping to . Start the giant-step value at and multiply it by once per increment of .
- •
- A match gives . Reduce modulo and verify . Membership and inverse assumptions must hold; a modulus itself is not the exponent search bound.
- •
- •
- •
Python
- •
def bsgs(g, h, p, n): import math m = math.isqrt(n) + 1 table = {} e = 1 for j in range(m): table.setdefault(e, j) e = (e * g) % p factor = pow(pow(g, m, p), -1, p) gamma = h for i in range(m): if gamma in table: return i * m + table[gamma] gamma = (gamma * factor) % p return None
- •
- •
- •
- •
Cards
- •
What's the time/space complexity of Baby-Step Giant-Step, and why is that an improvement over brute force?
- •
O(√n) instead of O(n) — trading brute-force's linear search for a meet-in-the-middle split into two √n-sized halves.
- •
- •
What does a "match" between the baby-step table and a giant-step value tell you?
- •
If h·g^(-im) equals table entry g^j, then the discrete log is x = im + j.
- •
- •