fork download
  1.  
  2. /* This program calculates the Key for two persons
  3. using the Diffie-Hellman Key exchange algorithm */
  4. #include<stdio.h>
  5. #include<math.h>
  6.  
  7. // Power function to return value of a ^ b mod P
  8. long long int power(long long int a, long long int b,
  9. long long int P)
  10. {
  11. if (b == 1)
  12. return a;
  13.  
  14. else
  15. return (((long long int)pow(a, b)) % P);
  16. }
  17.  
  18. //Driver program
  19. int main()
  20. {
  21. long long int P, G, x, a, y, b, ka, kb;
  22.  
  23. // Both the persons will be agreed upon the
  24. // public keys G and P
  25. P = 23; // A prime number P is taken
  26. printf("The value of P : %lld\n", P);
  27.  
  28. G = 9; // A primitve root for P, G is taken
  29. printf("The value of G : %lld\n\n", G);
  30.  
  31. // Alice will choose the private key a
  32. a = 4; // a is the chosen private key
  33. printf("The private key a for Alice : %lld\n", a);
  34. x = power(G, a, P); // gets the generated key
  35.  
  36. // Bob will choose the private key b
  37. b = 3; // b is the chosen private key
  38. printf("The private key b for Bob : %lld\n\n", b);
  39. y = power(G, b, P); // gets the generated key
  40.  
  41. // Generating the secret key after the exchange
  42. // of keys
  43. ka = power(y, a, P); // Secret key for Alice
  44. kb = power(x, b, P); // Secret key for Bob
  45.  
  46. printf("Secret key for the Alice is : %lld\n", ka);
  47. printf("Secret Key for the Bob is : %lld\n", kb);
  48.  
  49. return 0;
  50. }
  51.  
Success #stdin #stdout 0s 9424KB
stdin
Standard input is empty
stdout
The value of P : 23
The value of G : 9

The private key a for Alice : 4
The private key b for Bob : 3

Secret key for the Alice is : 9
Secret Key for the Bob is : 9