TExcelTAD
Home › Number Theory & Cryptography › Mini Project: A Toy Public-Key Toolkit

Mini Project: A Toy Public-Key Toolkit

This project builds a small public-key toolkit from the number theory of the course: Miller-Rabin prime generation, RSA key generation with CRT signing, Diffie-Hellman over a safe prime, ECDH on a toy elliptic curve, and two attacks that show why the real parameters are so large and why randomness matters.

Warning: This is teaching code. The sizes are tiny, the generators are seeded so the output is reproducible, and there is no padding, no constant-time arithmetic and no side-channel protection. Never use it to protect real data; use a vetted library such as cryptography or libsodium.

What we are building:

Step Part Course topics
1. Generate primes prime generation Miller-Rabin, the prime number theorem
2. RSA keys and CRT signatures RSA Euler's theorem, inverses, the CRT, hash-then-sign
3. Diffie-Hellman over a safe prime key exchange primitive roots, subgroups
4. ECDH on a toy curve elliptic curves point addition, scalar multiplication
5. Break it attacks shared factors, baby-step giant-step

Note: Each step is a complete program (the playground does not share variables between runs), so the helper functions are repeated where needed.

Step 1: Generate primes

A prime generator draws odd numbers of the right size with the top bit set and keeps the first one that passes Miller-Rabin with several bases (Generating Primes). By the prime number theorem about 1 in ln⁡2k/2\ln 2^{k} / 2 odd kk-bit numbers is prime, roughly 89 for k=256k = 256.

python · try it yourself
import random

def is_probable_prime(n, rng, rounds=20):
    if n < 2:
        return False
    for small in (2, 3, 5, 7, 11, 13, 17, 19, 23, 29):
        if n % small == 0:
            return n == small
    d, s = n - 1, 0
    while d % 2 == 0:
        d, s = d // 2, s + 1
    for _ in range(rounds):
        x = pow(rng.randrange(2, n - 1), d, n)
        if x in (1, n - 1):
            continue
        for _ in range(s - 1):
            x = x * x % n
            if x == n - 1:
                break
        else:
            return False
    return True

def gen_prime(bits, rng):
    tries = 0
    while True:
        tries += 1
        n = rng.getrandbits(bits) | (1 << (bits - 1)) | 1
        if is_probable_prime(n, rng):
            return n, tries

rng = random.Random(2026)            # seeded so the demo is reproducible; real keys use secrets
for bits in (64, 128, 256):
    p, tries = gen_prime(bits, rng)
    print(f"{bits}-bit prime after {tries:3d} candidates: {hex(p)[:18]}...")
64-bit prime after  49 candidates: 0xb6eafff5782afe6b...
128-bit prime after  21 candidates: 0xa606799cced8c284...
256-bit prime after 356 candidates: 0xb4acbd1e44487eb5...

The number of candidates is geometric with averages of about 22, 44 and 89, so it varies a lot: 356 for the 256-bit prime is an unlucky draw (about a 2 % chance), while 21 for the 128-bit one is lucky.

Step 2: RSA keys and CRT signatures

Key generation takes two 256-bit primes, e=65537e = 65537 and d=e−1 mod lcm⁡(p−1,q−1)d = e^{-1} \bmod \operatorname{lcm}(p - 1, q - 1) (RSA Key Generation). Signing hashes the message with SHA-256 and raises it to dd using the CRT (Faster RSA with the CRT); verification raises the signature to ee (RSA Signatures). A real scheme would use RSA-PSS padding (RSA Padding).

python · try it yourself
import random, hashlib, math

def is_probable_prime(n, rng, rounds=20):
    if n < 2 or any(n % s == 0 and n != s for s in (2, 3, 5, 7, 11, 13)):
        return n in (2, 3, 5, 7, 11, 13)
    d, s = n - 1, 0
    while d % 2 == 0:
        d, s = d // 2, s + 1
    for _ in range(rounds):
        x = pow(rng.randrange(2, n - 1), d, n)
        if x in (1, n - 1):
            continue
        for _ in range(s - 1):
            x = x * x % n
            if x == n - 1:
                break
        else:
            return False
    return True

def gen_prime(bits, rng):
    while True:
        n = rng.getrandbits(bits) | (1 << (bits - 1)) | 1
        if is_probable_prime(n, rng):
            return n

def rsa_keygen(bits, rng, e=65537):
    while True:
        p, q = gen_prime(bits // 2, rng), gen_prime(bits // 2, rng)
        lam = math.lcm(p - 1, q - 1)
        if p != q and math.gcd(e, lam) == 1:
            d = pow(e, -1, lam)
            return {"n": p * q, "e": e}, {"p": p, "q": q, "d": d}

def h(msg, n):
    return int.from_bytes(hashlib.sha256(msg).digest(), "big") % n

def sign(msg, pub, priv):
    p, q, d = priv["p"], priv["q"], priv["d"]
    m = h(msg, pub["n"])
    sp, sq = pow(m, d % (p - 1), p), pow(m, d % (q - 1), q)
    return sq + q * (pow(q, -1, p) * (sp - sq) % p)

def verify(msg, sig, pub):
    return pow(sig, pub["e"], pub["n"]) == h(msg, pub["n"])

rng = random.Random(7)
pub, priv = rsa_keygen(512, rng)
sig = sign(b"pay Bob 10", pub, priv)
print("modulus bits:", pub["n"].bit_length())
print("CRT signature equals plain one:", sig == pow(h(b"pay Bob 10", pub["n"]), priv["d"], pub["n"]))
print("verify original:", verify(b"pay Bob 10", sig, pub))
print("verify tampered:", verify(b"pay Bob 1000", sig, pub))
modulus bits: 512
CRT signature equals plain one: True
verify original: True
verify tampered: False

Step 3: Diffie-Hellman over a safe prime

A safe prime p=2q+1p = 2q + 1 (with qq prime) makes the group structure simple: g=4g = 4 generates the subgroup of prime order qq, so there are no small subgroups to leak bits (Diffie-Hellman Key Exchange).

python · try it yourself
import random

def is_probable_prime(n, rng, rounds=20):
    if n < 2 or any(n % s == 0 and n != s for s in (2, 3, 5, 7, 11, 13)):
        return n in (2, 3, 5, 7, 11, 13)
    d, s = n - 1, 0
    while d % 2 == 0:
        d, s = d // 2, s + 1
    for _ in range(rounds):
        x = pow(rng.randrange(2, n - 1), d, n)
        if x in (1, n - 1):
            continue
        for _ in range(s - 1):
            x = x * x % n
            if x == n - 1:
                break
        else:
            return False
    return True

def gen_safe_prime(bits, rng):
    tries = 0
    while True:
        tries += 1
        q = rng.getrandbits(bits - 1) | (1 << (bits - 2)) | 1
        if is_probable_prime(q, rng) and is_probable_prime(2 * q + 1, rng):
            return 2 * q + 1, q, tries

rng = random.Random(11)
p, q, tries = gen_safe_prime(96, rng)
g = 4
print(f"safe prime p = {p} ({p.bit_length()} bits, {tries} candidates for q)")
print("g has order q:", pow(g, q, p) == 1)

a, b = rng.randrange(2, q), rng.randrange(2, q)       # Alice's and Bob's secrets
A, B = pow(g, a, p), pow(g, b, p)                     # sent in the clear
print("Alice's key == Bob's key:", pow(B, a, p) == pow(A, b, p))
safe prime p = 48564541580114302323796153307 (96 bits, 969 candidates for q)
g has order q: True
Alice's key == Bob's key: True

Safe primes are much rarer than primes (both qq and 2q+12q + 1 must be prime), which is why real systems use fixed, published groups such as the RFC 3526 and RFC 7919 primes.

Step 4: ECDH on a toy curve

The course's toy curve y2=x3−3x+7y^2 = x^3 - 3x + 7 over F10007\mathbb{F}_{10007} has a prime number of points, N=10193N = 10193, so every point except the identity generates the whole group (Elliptic-Curve Diffie-Hellman).

python · try it yourself
import random, hashlib

p, a_coef, N, G = 10007, -3, 10193, (2, 3)

def add(P, Q):
    if P is None: return Q
    if Q is None: return P
    (x1, y1), (x2, y2) = P, Q
    if x1 == x2 and (y1 + y2) % p == 0: return None
    lam = ((3 * x1 * x1 + a_coef) * pow(2 * y1, -1, p) if P == Q else (y2 - y1) * pow(x2 - x1, -1, p)) % p
    x3 = (lam * lam - x1 - x2) % p
    return (x3, (lam * (x1 - x3) - y1) % p)

def mul(k, P):
    R = None
    for bit in bin(k)[2:]:
        R = add(R, R)
        if bit == "1": R = add(R, P)
    return R

rng = random.Random(42)
a, b = rng.randrange(1, N), rng.randrange(1, N)
A, B = mul(a, G), mul(b, G)
S1, S2 = mul(a, B), mul(b, A)
print("Alice public:", A, " Bob public:", B)
print("shared point equal:", S1 == S2, " N*G is the identity:", mul(N, G) is None)
key = hashlib.sha256(f"{S1[0]}".encode()).hexdigest()[:16]
print("derived key:", key)
Alice public: (1098, 8556)  Bob public: (9909, 4414)
shared point equal: True  N*G is the identity: True
derived key: 77b5939194797108

As in real ECDH, the shared xx-coordinate goes through a key-derivation function before use.

Step 5: Break it

Two attacks show what the real parameters protect against.

Shared factors. If two RSA moduli were generated with a weak seed and share a prime, one gcd factors both (GCD and Euclid's Algorithm).

Small groups. The toy curve has only 10193 points, so baby-step giant-step recovers an ECDH secret with at most about 2N≈2002\sqrt{N} \approx 200 point operations (119 below, because the giant steps stop at the first match) (Baby-Step Giant-Step). On a 256-bit curve the same attack needs about 21282^{128}.

python · try it yourself
import math, random
from sympy import nextprime

# Attack 1: two moduli that share a prime
shared = nextprime(2**255 + 12345)
n1 = shared * nextprime(2**255 + 999999)
n2 = shared * nextprime(2**255 + 31337 * 10**6)
g = math.gcd(n1, n2)
print("gcd reveals the shared prime:", g == shared, " n1 factored:", n1 == g * (n1 // g))

# Attack 2: baby-step giant-step on the toy curve
p, a_coef, N, G = 10007, -3, 10193, (2, 3)

def add(P, Q):
    if P is None: return Q
    if Q is None: return P
    (x1, y1), (x2, y2) = P, Q
    if x1 == x2 and (y1 + y2) % p == 0: return None
    lam = ((3 * x1 * x1 + a_coef) * pow(2 * y1, -1, p) if P == Q else (y2 - y1) * pow(x2 - x1, -1, p)) % p
    x3 = (lam * lam - x1 - x2) % p
    return (x3, (lam * (x1 - x3) - y1) % p)

def mul(k, P):
    R = None
    for bit in bin(k)[2:]:
        R = add(R, R)
        if bit == "1": R = add(R, P)
    return R

def neg(P):
    return None if P is None else (P[0], -P[1] % p)

secret = random.Random(42).randrange(1, N)            # Alice's key from Step 4
A = mul(secret, G)                                     # all the attacker sees

m = math.isqrt(N) + 1
baby, R = {}, None
for j in range(m):                                     # baby steps: jG
    baby.setdefault(R, j)
    R = add(R, G)
giant, Y, ops = neg(mul(m, G)), A, m
for i in range(m):                                     # giant steps: A - i*m*G
    if Y in baby:
        found = i * m + baby[Y]
        break
    Y, ops = add(Y, giant), ops + 1
print("recovered secret:", found, " correct:", found == secret, " point operations:", ops)
gcd reveals the shared prime: True  n1 factored: True
recovered secret: 1825  correct: True  point operations: 119

Where to go next

  • Replace the toy curve by P-256 or Curve25519 parameters and time one scalar multiplication; then estimate how long baby-step giant-step would take.
  • Add RSA-OAEP encryption and RSA-PSS signatures following RSA Padding, and check them against the cryptography package.
  • Implement ECDSA signing on the toy curve (ECDSA) and show that reusing a nonce reveals the private key.
  • Encrypt bits with the toy Regev scheme from Learning With Errors and compare key and ciphertext sizes with RSA and ECDH.
  • For the protocol side (TLS, certificates, password storage, secure coding) continue with Cybersecurity; for more proofs and counting arguments, see Discrete Mathematics.

Test yourself

Why does the prime generator set the top bit of each candidate?

  1. to make it odd
  2. to guarantee the number has exactly the requested bit length
  3. to speed up Miller-Rabin
  4. to make it a safe prime

Why is g=4g = 4 a good generator modulo a safe prime p=2q+1p = 2q + 1?

  1. it is a primitive root
  2. it is a square, so it generates the subgroup of prime order qq
  3. it is small
  4. it makes pp prime

Baby-step giant-step broke the toy ECDH key because…

  1. the curve equation was wrong
  2. the group has only about 10410^4 elements, so N\sqrt{N} is about 100
  3. the key was reused
  4. the hash was truncated