Simple RSA implementation with detail to readabiltiy, meant to demonstrate how the algorithm works. The C programming language was chosen for this implementation due to the similarity in syntax to other languages.
This was written for educational purposes. This implementation is vulnerable to countless cryptanalysis attacks, and is not considered secure nor intended for use in production systems.
THIS IS NOT MEANT TO BE USED AS A FUNCTIONAL PROGRAM, BUT RATHER A GUIDE TO UNDERSTANDING RSA. IT IS ASSUMED THE CODE WILL BE READ.
Two binaries can be built: rsa and rsa_tests. The first will produce a keypair given p and q, and a limit for the prime number generator used internally.
The RSA keypair is (e,n), (d,n).
The second binary was simply used to act as a very basic form of unit test ensuring encryption and decryption works.
This was written and tested on a Linux computer running Kernel 4.2. It should work on any Linux with gcc installed.
Care was taken to keep this program as simple as possible. No external libraries were used.
Based on: ((m**e)**d) % n = m e : encryption, d: decryption
Encryption: ciphertext = (message**e) % n
Decryption: (c**d == (m**e)**d == m) % n
p and q, two distinct prime numbers n = pq
fi is Euler's Totient Function fi(n) = fi(p) * fi(q) = (p - 1) * (q - 1) = n - (p + q - 1)
chose e, the public key so that:
1. 1 < e < fi(n)
2. gcd(e, fi(n)) == 1 (i.e. e and fi(n) are coprime
chose d, the private key so that:
1. d == (e \*\* -1) % fi(n)
...d is the modular multiplicative inverse of e modulo(fi(n))
Create RSA binary
make
Recompile RSA binary
make re
Create test binary
make tests
Recompile tests
make re-tests
Remove object files created durring build
make clean
Remove object files and binaries
make fclean
Directory / File | Description |
---|---|
src | Folder containing all the C source files |
include | Folder containing all the C include files |
Makefile | Configuration file for make command |
All functions related to the generation and verification of primes numbers.
Contains one global variable: g_prime_list used to store a list of prime numbers generated by sieve_of_eratosthenes
Function name | Description |
---|---|
gcd | Greatest common denominator |
is_prime | Verifies if number is prime |
sieve_of_eratosthenes | Generates a list of prime numbers, stored in g_prime_list |
All functions related to modular arithmetic used by the RSA algorithm.
Function name | Description |
---|---|
modular_exponent_simple | Simple implementation of modular exponent |
right_to_left | Optimized implementation of modular exponent |
modular_inverse | Implementation of modular inverse |
Contains the actual RSA algorithm
Function name | Description |
---|---|
pick_e | Simple algorithm used by rsa_keygen to select value e |
rsa_keygen | Implementation of the RSA key generation algorithm |
rsa_encrypt | Implementation of RSA encryption |
rsa_decrypt | Implementation of RSA decryption |