Write a C program to implement RSA Cryptosystem and demonstrate the encryption/d
ID: 3825281 • Letter: W
Question
Write a C program to implement RSA Cryptosystem and demonstrate the encryption/decryption of the input plaintext message of upto a maximum of 20 characters. The program then asks the user to input the following and does appropriate validation of the input as per the requirements of the RSA algorithm before proceeding further with encryption: (1) the prime factors p and q (data type long) and the encryption exponent e. Obviously, as part of the design your program must also compute the (a) Euler's Totient function phi(n), (b) check whether gcd(e, phi (n)) = 1 and (c) compute the decryption key (d, n) such that d = e^-1 mod phi (n) (d to be computed using the Extended Euclidean algorithm to find inverse). The program must output the computed ciphertext and then decrypt the ciphertext and print the decrypted plaintext message.Explanation / Answer
Here is the C code for RSA Algorithm:-
#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
#include<math.h>
#include<string.h>
long int p,q,n,t,flag,e[100],d[100],temp[100],j,m[100],en[100],i;
char msg[100];
int prime(long int);
void ce();
long int cd(long int);
void encryption();
void decryption();
void main() {
clrscr();
printf(“ Enter first prime: ”);
scanf("%d",&p);
flag=prime(p);
if(flag==0) {
printf(" WRONG INPUT ");
getch();
exit(1);
}
printf(“ Enter second prime: ”);
scanf("%d",&q);
flag=prime(q);
if(flag==0||p==q) {
printf(" WRONG INPUT ");
getch();
exit(1);
}
printf(“ Enter message for encryption ");
fflush(stdin);
scanf("%s",msg);
for (i=0;msg[i]!=NULL;i++)
m[i]=msg[i];
n=p*q;
t=(p-1)*(q-1);
ce();
printf(" POSSIBLE VALUES OF e AND d ARE ");
for (i=0;i<j-1;i++)
printf(" %ld %ld",e[i],d[i]);
decryption();
encryption();
getch();
}
int prime(long int pr) {
int i;
j=sqrt(pr);
for (i=2;i<=j;i++) {
if(pr%i==0)
return 0;
}
return 1;
}
void ce() {
int k;
k=0;
for (i=2;i<t;i++) {
if(t%i==0)
continue;
flag=prime(i);
if(flag==1&&i!=p&&i!=q) {
e[k]=i;
flag=cd(e[k]);
if(flag>0) {
d[k]=flag;
k++;
}
if(k==99)
break;
}
}
}
long int cd(long int x) {
long int k=1;
while(1) {
k=k+t;
if(k%x==0)
return(k/x);
}
}
void encryption() {
long int pt,ct,key=e[0],k,len;
i=0;
len=strlen(msg);
while(i!=len) {
pt=m[i];
pt=pt-96;
k=1;
for (j=0;j<key;j++) {
k=k*pt;
k=k%n;
}
temp[i]=k;
ct=k+96;
en[i]=ct;
i++;
}
en[i]=-1;
printf(" THE ENCRYPTED MESSAGE IS ");
for (i=0;en[i]!=-1;i++)
printf("%c",en[i]);
}
void decryption() {
long int pt,ct,key=d[0],k;
i=0;
while(en[i]!=-1) {
ct=temp[i];
k=1;
for (j=0;j<key;j++) {
k=k*ct;
k=k%n;
}
pt=k+96;
m[i]=pt;
i++;
}
m[i]=-1;
printf(" THE DECRYPTED MESSAGE IS ");
for (i=0;m[i]!=-1;i++)
printf("%c",m[i]);
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.