This is a project based on my SRP (specialised study project) from Danish high school. The code implementation can be fund under the folder python_code.
RSA encryption
RSA encryption is developed by Ron Rivest, Adi Shamir and Len Adleman in 1977. It is based on the prime factorization problem. In order to encrypt and decrypt, two public keys๐๐ ($n$, $e$) and a private key๐ $d$ is needed. They can be fund by the following steps:
Choose two prime numbers $p$ and $q$, the set $n=p\cdot q$
Calculate $\phi(n) = (p - 1)(q - 1)$
Choose a whole number, so $0 < e <\phi(n)$ and $\text{gcd}(e, \phi(n)) = 1$
Calculate $d$ so, $ed \equiv 1 (\text{mod } \phi(n))$
Now that the keys are fund, we can use them to encrypt. As follows
$$
c = m^e (\text{mod } n)
$$
where $m$ is the messeage and $0 < m < n$. Note that $m$ needs to be smaller than $n$. This is why my implementation of RSA splits each sentence into individual letter.
When decrypting we use
$$
m = c^d (\text{mod } n)
$$
Why does this work? Let start by substituting $c$ in when calculating $m$
Since $\text{gcd}(m, n) = 1$, we can rewrite $m$ as
$$
m = m^{ed(\text{mod } \phi(n))}(\text{mod } n)
$$
The key $d$ is chosen such that $ed \equiv 1 (\text{mod } \phi(n))$. This can also be written as $ed(\text{mod } \phi(n)) = 1$.
Therefore we can now write
$$
m = m^{1}(\text{mod } n) = m (\text{mod } n)
$$
This only applies when $\text{gcd}(e, \phi(n) = 1)$.
The prime factorization problem
To break the RSA encryption we need to find the private key $d$, which is calculated based on $e$ and $\phi(n)$. Luckily we know the $e$ as it is a public key. So, we "only" need to find $\phi(n)$. We know $\phi(n) = (p-1)(q-1)$. This means we need to find $p$ and $q$ in order to find $\phi(n)$. This is where the other key $n$ comes into play. We know
$$
n = p\cdot q
$$
We can use Fermat's method to find $p$ and $q$. Fermat's method tells us that $n$ is an uneven whole number, that can factorized only if there is a solution to $n = x^2-y^2$ where $x$ and $y$ must be whole numbers. Since $x$ and $y$ ar whole number $n$ can be written as
$$
n = x^2-y^2 = (x+y)(x-y)
$$
To find $x$ and $y$ we use
$$
x^2 - n = y^2
$$
When a solution where $x$ and $y$ are whole numbers is fund, we can now find $p$ and $q$