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 and primitive root . Then:
- Alice picks secret , computes , sends to Bob
- Bob picks secret , computes , sends to Alice
- Both compute the shared secret:
An eavesdropper sees but computing from requires solving the discrete logarithm — believed to be hard for large primes.
ElGamal Encryption
Built on top of Diffie-Hellman:
Key Generation: Choose prime , generator , secret key . Public key is .
Encrypt message (where ):
- Pick random
- Ciphertext is
Decrypt:
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.