Lesson 9 of 15

ElGamal Encryption

ElGamal Encryption

The ElGamal cryptosystem (Taher ElGamal, 1985) is a public-key scheme based on the Discrete Logarithm Problem, like Diffie-Hellman. Unlike RSA, ElGamal encryption is probabilistic — the same plaintext encrypted twice produces different ciphertexts (due to the random kk), which is a security advantage.

Key Generation

Choose a prime pp, generator gg, and private key xx. The public key is:

y=gx mod py = g^x \bmod p

Encryption

To encrypt message mm with public key yy, choose a random session key kk:

c1=gk mod pc_1 = g^k \bmod p c2=m⋅yk mod pc_2 = m \cdot y^k \bmod p

The ciphertext is the pair (c1,c2)(c_1, c_2).

Decryption

Using private key xx:

m=c2⋅c1−x mod pm = c_2 \cdot c_1^{-x} \bmod p

Since c1=gkc_1 = g^k and y=gxy = g^x:

c1x=gkx=ykc_1^x = g^{kx} = y^k

So c2⋅c1−x=m⋅yk⋅y−k=mc_2 \cdot c_1^{-x} = m \cdot y^k \cdot y^{-k} = m. ✓

Computing c1−x mod pc_1^{-x} \bmod p

By Fermat's Little Theorem, c1p−1≡1(modp)c_1^{p-1} \equiv 1 \pmod{p}, so c1−x≡c1p−1−x(modp)c_1^{-x} \equiv c_1^{p-1-x} \pmod{p}.

Example

p=23p=23, g=5g=5, private key x=6x=6, public key y=56 mod 23=8y = 5^6 \bmod 23 = 8.

Encrypt m=10m=10 with session key k=3k=3:

  • c1=53 mod 23=10c_1 = 5^3 \bmod 23 = 10 · c2=10⋅83 mod 23=10⋅6 mod 23=14c_2 = 10 \cdot 8^3 \bmod 23 = 10 \cdot 6 \bmod 23 = 14

Decrypt (10,14)(10, 14): 14⋅1023−1−6 mod 23=14⋅1016 mod 23=1014 \cdot 10^{23-1-6} \bmod 23 = 14 \cdot 10^{16} \bmod 23 = 10 ✓

Your Task

Implement:

  • elgamal_encrypt(m, g, pub_key, k, p) → (c1, c2)
  • elgamal_decrypt(c1, c2, priv_key, p) → m
Python runtime loading...
Loading...
Click "Run" to execute your code.