int main() { int XA, XB, YA, YB, ka, kb; printf("Enter the global prime q : "); scanf("%d", &q); a = primitiveRoot(q); srand(time(NULL)); //the private keys XA = (rand() % (q - 1)) + 1; XB = (rand() % (q - 1)) + 1; //the public keys YA = abmodn(a, XA, q); YB = abmodn(a, XB, q); //calculation of keys ka = abmodn(YB, XA, q); kb = abmodn(YA, XB, q); printf("XA = %d\nXB = %d\nYA = %d\nYB = %d\nka = %d\nkb = %d\n", XA, XB, YA, YB, ka, kb); if(ka == kb) { printf("Diffie hellman executed correctly :\nka = kb = %d\n", ka, kb); } else { printf("There was some problem. Quitting quitely\n"); return -1; } return 0; }
//returns x: x^k = a mod mod, mod is prime int discreteRoot(int a, int k, int mod) { if (a == 0) return 0; int g = primitiveRoot(mod); int y = discreteLogariphm(power(g, k, mod), a, mod); return power(g, y, mod); }