fork download
  1.  
  2. #include <bits/stdc++.h>
  3. using namespace std;
  4.  
  5. // Check Prime Number
  6. bool isPrime(long long n) {
  7. if(n <= 1) {
  8. return false;
  9. }
  10.  
  11. for(long long i = 2; i * i <= n; i++) {
  12. if(n % i == 0) {
  13. return false;
  14. }
  15. }
  16.  
  17. return true;
  18. }
  19.  
  20. // Modular Exponentiation
  21. long long modPow(long long base, long long exp, long long mod) {
  22. base %= mod;
  23. long long ans = 1;
  24.  
  25. while(exp >= 1) {
  26. if(exp % 2 == 1) {
  27. ans = (ans * base) % mod;
  28. }
  29.  
  30. base = (base * base) % mod;
  31. exp /= 2;
  32. }
  33.  
  34. return ans;
  35. }
  36.  
  37. // Check Primitive Root
  38. bool isPrimitiveRoot(long long g, long long p) {
  39. set<long long> values;
  40.  
  41. for(long long i = 1; i < p; i++) {
  42. values.insert(modPow(g, i, p));
  43. }
  44.  
  45. return values.size() == p - 1;
  46. }
  47.  
  48. int main() {
  49. long long p, g, a, b;
  50.  
  51. cout << "Enter prime number (p): ";
  52. cin >> p;
  53.  
  54. if(!isPrime(p)) {
  55. cout << "p is not a prime number!";
  56. return 0;
  57. }
  58.  
  59. cout << "Enter primitive root (g): ";
  60. cin >> g;
  61.  
  62. if(g <= 0 || g >= p || !isPrimitiveRoot(g, p)) {
  63. cout << "Invalid primitive root!";
  64. return 0;
  65. }
  66.  
  67. // Private Keys
  68. cout << "Enter Alice's private key: ";
  69. cin >> a;
  70.  
  71. cout << "Enter Bob's private key: ";
  72. cin >> b;
  73.  
  74. if(a <= 0 || b <= 0) {
  75. cout << "Private keys must be positive!";
  76. return 0;
  77. }
  78.  
  79. // Generate Public Keys
  80. long long A = modPow(g, a, p);
  81. long long B = modPow(g, b, p);
  82.  
  83. cout << "\nAlice's Public Key = " << A << endl;
  84. cout << "Bob's Public Key = " << B << endl;
  85.  
  86. // Generate Shared Secret Keys
  87. long long keyAlice = modPow(B, a, p);
  88. long long keyBob = modPow(A, b, p);
  89.  
  90. cout << "\nAlice's Shared Key = " << keyAlice << endl;
  91. cout << "Bob's Shared Key = " << keyBob << endl;
  92.  
  93. if(keyAlice == keyBob) {
  94. cout << "\nShared Secret Key = " << keyAlice << endl;
  95. cout << "Key Exchange Successful!";
  96. }
  97. else {
  98. cout << "Key Exchange Failed!";
  99. }
  100.  
  101. return 0;
  102. }
  103.  
Success #stdin #stdout 0s 544KB
stdin
Standard input is empty
stdout
Enter prime number (p): p is not a prime number!