Sunday, August 9, 2020

Simple Diffie–Hellman Key Exchange Example in C++.

Diffie-Hellman Key Exchange Method C++


DiffieHellman key exchange method allows two parties that have no prior knowledge of each other to jointly establish a shared secret key over an insecure channel. This key can then be used to encrypt subsequent communications using a symmetric key cipher.



EXAMPLE :-

#include<iostream>
#include<cstdio>
using namespace std;
class DiffieHellman
{
       public:
              long long int p1,g1,x1,a,y1,b,M,N;
              DiffieHellman(long long int ph,long long int gh,
                long long int xh,long long int yh)
                      {
                     p1 = ph;
                     g1 = gh;
                     x1 = xh;
                     y1 = yh;
                     a=power(g1,x1,p1);
                     b=power(g1,y1,p1);
                     M = power(b,x1,p1);
                     N = power(a,y1,p1);
              }
              long long int power(int a,int b,int mod)
              {
                     long long int s;
                     if(b==1)
                           return a;
                     s=power(a,b/2,mod);
                     if(b%2==0)
                           return (s*s)%mod;
                     else
                           return (((s*s)%mod)*a)%mod;
              }
};

int main()
{
       long long int p1,g1,x1,a,y1,b,M,N;
      
       cout<<"Enter the values of p1 and g1 upon which Alice And Bob both will Agree :: "<<endl;
       cin>>p1>>g1;
      
       cout<<"Enter the Secret Integer for Alice :: ";
       cin>>x1;
       cout<<"Enter the Secret Integer for Bob :: ";
       cin>>y1;
       cout<<endl;
       DiffieHellman dha(p1,g1,x1,y1);
      
       cout<<"Alice's private key, known only to Alice :: "<<dha.a<<endl;
       cout<<"Bob's private key known only to Bob :: "<<dha.b<<endl;
       cout<<endl;
       cout<<"Alice's public key, known to Alice and Bob :: "<<dha.M<<endl;
       cout<<"Bob's public key, known to Alice and Bob :: "<<dha.N<<endl;

       return 0;
}


OUTPUT

Enter the values of p1 and g1 upon which Alice And Bob both will Agree :: 
7
3 
Enter the Secret Integer for Alice :: 3
Enter the Secret Integer for Bob :: 7

Alice's private key, known only to Alice :: 6
Bob's private key known only to Bob :: 3

Alice's public key, known to Alice and Bob :: 6
Bob's public key, known to Alice and Bob :: 6


No comments:

Post a Comment

Please do not any spam link in Comment Box