This code implements a simple RSA encryption and decryption system,which includes
functions for modular
exponentiation, computing modular inverses,calculating the GCD, and generating RSA
keys.
1. Code Structure :
mod_expo: This function performs modular exponentiation, which calculates a^b(mod
n) efficiently
This is crucial for both encryption and decryption, as large powers of numbers need
to be reduced modulo
n in RSA operations.
mod_inv: Uses the Extended Euclidean Algorithm to find the modular inverse of a
under modulo phi.This is
used to calculate the private key d in RSA, where d is the modular inverse of e
modulo phi.
gcd: Calculates the GCD (Greatest Common Divisor) of two numbers. This is used to
ensure that e(public exponent)
is coprime to phi in the RSA setup.
generatekeys: Generates the RSA public and private keys. It calculates n=p×q and
ϕ=(p−1)×(q−1),
then finds an appropriate e such that 1<e<ϕ and gcd(e,ϕ)=1. Finally, it calculates
d as the modular inverse of
e modulo phi.
main: Drives the program by setting prime numbers p and q, generating keys, and
performing encryption and
decryption on a message.
2. Explanation of Key Functions :
mod_expo(ll a, ll b, ll mod) :This function uses the "Exponentiation by Squaring"
method to compute a^b(mod n)
ans accumulates the result.
The loop iteratively squares a and reduces b until b=0, reducing each intermediate
result by mod to prevent
overflow.
mod_inv(ll a, ll phi) :Uses the Extended Euclidean Algorithm to find the modular
inverse of a under modulo phi.
The modular inverse is necessary to find d in RSA, ensuring that d×e≡1modϕ.
gcd(ll a, ll b) :Implements the Euclidean Algorithm for finding the GCD, which
ensures that e and phi are
coprime. It is crucial for ensuring that the selected public exponent e is valid.
generatekeys(ll p, ll q, ll *n, ll *e, ll *d) : This function generates RSA keys:-
-Calculates n and phi.
-Iteratively finds an appropriate value for e by ensuring gcd(e,ϕ)=1.
-Computes the private exponent d as the modular inverse of e modulo phi.
main :
In main, the program initializes primes p and q, generates keys, and then encrypts
and decrypts a sample
message (ASCII 65 for 'A'):
Encrypts the message using message^e(mod n)
Decrypts using encrypted_message^d(mod n)
3.Sample Output :
with p=61,q=53,message='A'(ASCII value of A) :-
Public Key (n, e): (3233, 7)
Private Key (n, d): (3233, 1783)
Original Message: 65
Encrypted Message: 2790
Decrypted Message: 65
4.Summary :
This code effectively demonstrates RSA encryption and decryption in a simplified
form. Key areas for
improvement include adding error handling, larger default values for e, and
enhanced security practices
for practical use.