-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathDeffieHellman.cpp
64 lines (59 loc) · 1.43 KB
/
DeffieHellman.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
#include<iostream>
#include<unordered_map>
#include<vector>
using namespace std;
int calculatePow(int x, int n,int q) {
int num=x;
if(n==0)return 1;
int ans=1;
while(n>0){
if(n%2){
ans=(ans*x)%q;
n=n-1;
}else{
x=x*x;
n=n/2;
}
}
return ans;
}
int main(){
int q;
vector<int>alphas;
cout<<"Enter the prime number"<<endl;
cin>>q;
for(int alpha=3;alpha<q;alpha++){
unordered_map<int,int>hash;
int flag=1;
for(int i=1;i<q;i++){
int num=calculatePow(alpha,i,q);
num=num%q;
if(hash.find(num)!=hash.end()){
flag=0;
break;
}else{
hash[num]=1;
}
}
if(flag){
alphas.push_back(alpha);
}
}
cout<<"Primitive Roots are"<<endl;
for(auto it:alphas){
cout<<it<<" ";
}
cout<<endl;
int privateKeyA,privateKeyB;
cout<<"Enter the private key of Sender"<<endl;
cin>>privateKeyA;
cout<<"Enter the private key of Receiver"<<endl;
cin>>privateKeyB;
int publicKeyA=calculatePow(alphas[0],privateKeyA,q)%q;
int publicKeyB=calculatePow(alphas[0],privateKeyB,q)%q;
int senderKey=calculatePow(publicKeyB,privateKeyA,q)%q;
int receiverKey=calculatePow(publicKeyA,privateKeyB,q)%q;
cout<<"Sender Key1 "<<senderKey<<endl;
cout<<"Receiver Key1 " <<receiverKey<<endl;
return 0;
}