Discrete Logarithm — Baby-Step Giant-Step
Tutorial Video
Text description (accessibility)
This video demonstrates the "Discrete Logarithm — Baby-Step Giant-Step" functional Rust example. Difficulty level: Fundamental. Key concepts covered: Functional Programming. Given g, h, and prime p, the discrete logarithm problem asks: find x such that `g^x ≡ h (mod p)`. Key difference from OCaml: | Aspect | Rust | OCaml |
Tutorial
The Problem
Given g, h, and prime p, the discrete logarithm problem asks: find x such that g^x ≡ h (mod p). This is computationally hard for large p (the Discrete Log Problem, DLP), which is the security foundation of Diffie-Hellman key exchange, ElGamal encryption, DSA signatures, and elliptic curve cryptography. Baby-step Giant-step (BSGS) solves the DLP in O(sqrt(p)) time and O(sqrt(p)) space — much faster than brute force O(p) but still infeasible for cryptographic p (256+ bit). Understanding BSGS is essential for cryptanalysis, CTF competitions, and understanding why large primes are necessary.
🎯 Learning Outcomes
h * g^j mod p for j = 0..m into a hash mapg^(i*m) mod p and look up in the baby-step tableCode Example
#![allow(clippy::all)]
//! PlaceholderKey Differences
| Aspect | Rust | OCaml |
|---|---|---|
| Baby step table | HashMap<u64, u64> | Hashtbl (int, int) |
| m computation | (p as f64).sqrt().ceil() | float_of_int |> sqrt |> ceil |
| Giant step iteration | Multiply by precomputed gm | Same approach |
| No solution | Returns None | Returns None |
| Large p support | Limited to u64 | Zarith for large p |
| Complexity | O(sqrt(p)) time+space | Same |
OCaml Approach
OCaml implements BSGS with Hashtbl.t for baby steps: Hashtbl.add table val j. The giant step loop uses for i = 1 to m do ... done. OCaml's float_of_int |> sqrt |> ceil |> int_of_float computes m. The Hashtbl.find_opt table giant returns int option. OCaml's Zarith handles large moduli beyond 63-bit integers. The baby-step table uses Hashtbl.replace to handle collisions where multiple j values give the same baby step (take the smallest j).
Full Source
#![allow(clippy::all)]
//! PlaceholderDeep Comparison
OCaml vs Rust: Discrete Log Bsgs
Overview
See the example.rs and example.ml files for detailed implementations.
Key Differences
| Aspect | OCaml | Rust |
|---|---|---|
| Type system | Hindley-Milner | Ownership + traits |
| Memory | GC | Zero-cost abstractions |
| Mutability | Explicit ref | mut keyword |
| Error handling | Option/Result | Result<T, E> |
See README.md for detailed comparison.