RSA (Rivest-Shamir-Adleman) cryptosystem
It is a public key cryptosystem (so it has a private key and a public key), it was constructed in 1977 by Rivest, Shamir and Adleman. Every public key cryptosystem relies heavily on a trapdoor function and RSA is secure because of the integer factorization problem. Which consist in validating the result by multiplying two numbers and that is easy but finding the factors is hard.
Let's have p be a prime number than for any integer a (a is not divisible by p) the number ap-1-1 is an integer multiple of p.
ap-1 ≡ 1 (mod p) which is Fermat's Little Theorem. We can generalize this theorem with Euler's Φ(n) function : this totient function counts the positive integers up to a given integer n that are relative prime to n and the formula is : aΦ(n) ≡ 1 (mod p). Notably by relative prime we mean that two integers a and b are said to be relative prime or coprime if the only positive integer (factor) that divides both of them is 1 with this formula : gcd(a, b) = 1
-
We generate 2 large prime numbers p and q, for this we can use Rabin-Miller very optimized algorithm to do so.
-
We calculate n = p * q so let's multiply the prime numbers : Φ(n) = (p - 1) * (q - 1)
-
Let's calculate the public key e parameter, we can calculate e such that gcd(e, Φ(n)) = 1. So basically e and Φ(n) are relative primes.
-
Let's calculate the private key d parameter : let's calculate the modular inverse of e (this is why it is crucial that e and Φ(n) are coprime) : d * e mod Φ(n) = 1, after solving this equation we get the d parameter.
Then we have PUBLIC KEY : (e, n) and PRIVATE KEY : (d, n)
After those steps, to encrypt the message we first have to transform the plaintext into blocks (we can use ASCII table to convert text into numbers) where every block is smaller than n and as usual we use the public key for encryption and the private key for the decryption. That way ciphertext_block = plaintext_blocke mod n and plaintext_block = ciphertext_blockd mod n
-
We talked a lot, now let's try this in a real example, let's generate large prime numbers : p = 17 and q = 23.
-
Let's calculate n = p * q = 17 * 23 = 391 so Φ(17 - 1) * (23-1) = 352.
-
We have to find now an e number where gcd(e, Φ(n)) = 1 with Euclide Algorithm and we get e = 21.
-
We finally have to find the modular inverse of e using Extended Euclidean Algorithm and we get d = 285
Now that we have the Public key : (21, 391) and Private key : (285, 391) we can encrypt a message.
Let's say we have the character a to encrypt. The ASCII representation of a is 97.
Encryption → ciphertext_block = plaintext_blocke mod n = 9721 mod 391 = 37
Decryption → plaintext_block = ciphertext_blockd mod n = 37285 mod 391 = 97