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=gxmodpy = g^x \bmod p

Encryption

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

c1=gkmodpc_1 = g^k \bmod p c2=mykmodpc_2 = m \cdot y^k \bmod p

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

Decryption

Using private key xx:

m=c2c1xmodpm = 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 c2c1x=mykyk=mc_2 \cdot c_1^{-x} = m \cdot y^k \cdot y^{-k} = m. ✓

Computing c1xmodpc_1^{-x} \bmod p

By Fermat's Little Theorem, c1p11(modp)c_1^{p-1} \equiv 1 \pmod{p}, so c1xc1p1x(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=56mod23=8y = 5^6 \bmod 23 = 8.

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

  • c1=53mod23=10c_1 = 5^3 \bmod 23 = 10 · c2=1083mod23=106mod23=14c_2 = 10 \cdot 8^3 \bmod 23 = 10 \cdot 6 \bmod 23 = 14

Decrypt (10,14)(10, 14): 14102316mod23=141016mod23=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.