Lesson 15 of 15

Applications to Cryptography

Applications to Cryptography

Abstract algebra underpins modern cryptography. Let's implement two foundational protocols using finite field arithmetic.

Diffie-Hellman Key Exchange

Two parties (Alice and Bob) agree on a public prime pp and primitive root gg. Then:

  1. Alice picks secret aa, computes A=gamodpA = g^a \bmod p, sends AA to Bob
  2. Bob picks secret bb, computes B=gbmodpB = g^b \bmod p, sends BB to Alice
  3. Both compute the shared secret: s=Bamodp=Abmodp=gabmodps = B^a \bmod p = A^b \bmod p = g^{ab} \bmod p

An eavesdropper sees g,p,A,Bg, p, A, B but computing aa from A=gamodpA = g^a \bmod p requires solving the discrete logarithm — believed to be hard for large primes.

ElGamal Encryption

Built on top of Diffie-Hellman:

Key Generation: Choose prime pp, generator gg, secret key xx. Public key is h=gxmodph = g^x \bmod p.

Encrypt message mm (where 1m<p1 \le m < p):

  1. Pick random kk
  2. c1=gkmodpc_1 = g^k \bmod p
  3. c2=(mhk)modpc_2 = (m \cdot h^k) \bmod p
  4. Ciphertext is (c1,c2)(c_1, c_2)

Decrypt: m=c2(c1x)1modp=c2c1p1xmodpm = c_2 \cdot (c_1^x)^{-1} \bmod p = c_2 \cdot c_1^{p-1-x} \bmod p

Modular Exponentiation

Both protocols rely on fast modular exponentiation:

def mod_pow(base, exp, mod):
    result = 1
    base = base % mod
    while exp > 0:
        if exp & 1:
            result = (result * base) % mod
        exp >>= 1
        base = (base * base) % mod
    return result

Your Task

Implement diffie_hellman(g, p, a, b) returning the shared secret, and elgamal_encrypt(p, g, h, m, k) / elgamal_decrypt(p, x, c1, c2) for ElGamal encryption.

Pyodide loading...
Loading...
Click "Run" to execute your code.