Name=Rajas anakkachery
Reg no=21BCE2224
Elgamal
PROGRAM
#include <iostream>
using namespace std;
#include<cmath>
int findMod(int dividend, int divisor) {
int modulus = dividend % divisor;
if (modulus < 0 && divisor > 0) {
modulus += divisor;
}
return modulus;
}
int extendedEuclidean(int r1, int r2, int t1, int t2) {
int t, quotient, temp;
int ans;
while (r2 != 0) {
quotient = r1 / r2;
temp = r2;
r2 = r1 % r2;
r1 = temp;
temp = t2;
t2 = t1 - t2 * quotient;
t1 = temp;
}
return t1;
}
int main(){
int b,c,d,k,q,M,alpha,private_key,a,public_key,K,c1,c2,inverse,inverse1,e,K1,M1;
cout<<"enter a prime number(q): "<<endl;
cin>>q;
cout<<"enter the primitive root of q: "<<endl;
cin>>alpha;
cout<<"select a private key(between 1 and q-1): "<<endl;
cin>>private_key;
a=pow(alpha,private_key);
public_key=findMod(a,q);
// encryption
cout<<"enter value of M(M<q): "<<endl;
cin>>M;
cout<<"enter the k value(1<=k<=q-1): "<<endl;
cin>>k;
b=pow(public_key,k);
K=findMod(b,q);
c=pow(alpha,k);
c1=findMod(c,q);
d=K*M;
c2=findMod(d,q);
cout<<"c1= "<<c1<<endl;
cout<<"c2= "<<c2<<endl;
// decryption
e=pow(c1,private_key);
K1=findMod(e,q);
cout<<"checking"<<endl;
cout<<"K: "<<K<<endl;
cout<<"K1: "<<K1<<endl;
inverse= extendedEuclidean(q,K1,0,1);
if(inverse<0){
inverse=inverse+q;
}
inverse1=c2*inverse;
M1=findMod(inverse1,q);
cout<<"checking"<<endl;
cout<<"M: "<<M<<endl;
cout<<"M1: "<<M1<<endl;
OUTPUT