Enrollment No.
:230843116012
PRACTICAL – 1
AIM:-Implement RSA algorithm.
Take two prime numbers p,q
n=pxq
Initially take encryption key such that it is relatively prime with ф(n).
Find out decryption key.
Take plaintext message M, Ciphertext C=Me mod n.
To get plaintect from ciphertext M=Cd mod n.
Test case :
Two prime numbers 17,11
Encryption key = 7
Decryption key = 23
M=88
C=11
CODE:-
#include<stdio.h>
int gcd(int a, int b) {
if (b == 0) return a;
return gcd(b, a % b);
}
int modInverse(int e, int phi) {
int t1 = 0, t2 = 1;
int r1 = phi, r2 = e;
while (r2 > 0) {
int quotient = r1 / r2;
int temp_r = r1 % r2;
int temp_t = t1 - quotient * t2;
r1 = r2;
r2 = temp_r;
t1 = t2;
t2 = temp_t;
}
if (r1 > 1) {
printf("No modular inverse exists\n");
return -1;
}
if (t1 < 0) {
t1 += phi;
}
return t1;
}
1
Enrollment No.:230843116012
int modExp(int base, int exp, int mod) {
int result = 1;
while (exp > 0) {
if (exp % 2 == 1) {
result = (result * base) % mod;
}
base = (base * base) % mod;
exp /= 2;
}
return result;
}
int main() {
int p, q;
printf("Enter the first prime number (p): ");
scanf("%d", &p);
printf("Enter the second prime number (q): ");
scanf("%d", &q);
int n = p * q;
int phi_n = (p - 1) * (q - 1);
printf("Calculated φ(n) = (p - 1) * (q - 1) = %d\n", phi_n);
int e;
do {
printf("Enter the encryption key (e): ");
scanf("%d", &e);
if (gcd(e, phi_n) != 1) {
printf("e must be relatively prime to φ(n), try again.\n");
}
} while (gcd(e, phi_n) != 1);
int d = modInverse(e, phi_n);
if (d == -1) {
return -1;
}
printf("Decryption key (d): %d\n", d);
int M;
printf("Enter the plaintext message (M): ");
scanf("%d", &M);
int C = modExp(M, e, n);
printf("Ciphertext (C): %d\n", C);
int decryptedMessage = modExp(C, d, n);
printf("Decrypted Message (M'): %d\n", decryptedMessage);
if (M == decryptedMessage) {
printf("Decryption successful: The decrypted message matches the original.\n");
} else {
printf("Decryption failed: The decrypted message does not match the
original.\n");
}
2
Enrollment No.:230843116012
return 0;
}
OUTPUT