# Cryptography/ElGamal

ElGamal is one of the simplest cryptosystems based on the discrete logarithm problem. A quick reminder of the discrete logarithm problem - given ${\displaystyle g,h\in G}$, such that ${\displaystyle h=g^{x}}$, find ${\displaystyle x}$. This is a hard problem when dealing with finite sets. ElGamal has a set of public parameters which can be shared by a number of users of the system. These are referred to as the domain parameters. These parameters are:

- ${\displaystyle p}$ - a large prime of around 1024 bits (currently) such that ${\displaystyle p-1}$ is divisible by another prime ${\displaystyle q}$ of around 160 bits.
- ${\displaystyle g}$ - an element of the finite field ${\displaystyle F_{p}^{*}}$ with order divisible by ${\displaystyle q}$, that is ${\displaystyle g^{(p-1)/q}(modp)\neq 1}$.


The domain parameters create a public group ${\displaystyle G}$ with a prime order ${\displaystyle q}$ and a generator ${\displaystyle g}$. In other words, we create a large but finite group, and a method of ordering that group (the generator), and we know that it will contain a prime number of elements. These are the properties we are after. These parameters are public, and the security of the system depends on the public and private key pair, which we shall generate next.

The private key ${\displaystyle x}$ is a randomly-chosen integer. The public key is ${\displaystyle h=g^{x}(modp)}$.

In order to encrypt a message ${\displaystyle m}$ we generate a random ephemeral key ${\displaystyle k}$, and calculate: ${\displaystyle c_{1}=g^{k}c_{2}=m*h^{k}}$

This gives us the ciphertext ${\displaystyle c=(c_{1},c_{2})}$.

In order to decrypt a ciphertext we compute: ${\displaystyle {\frac {c_{2}}{c_{1}^{x}}}={\frac {m*h^{k}}{g^{x*k}}}={\frac {m*g^{x*k}}{g^{x*k}}}=m}$

As you can see from the decryption method, the message 0 will encrypt to itself, so not a good choice of message. In addition to this, as a result of using the ephemeral key ${\displaystyle k}$, which will change every time you can see that the same message ${\displaystyle m}$ will encrypt to many different ciphertexts.

Since the ciphertext is expressed as 2 integers of the same length as the message, we end up with ciphertexts being twice as large as the message they're encrypting.