aboutsummaryrefslogtreecommitdiff
path: root/q8/dh.c
diff options
context:
space:
mode:
Diffstat (limited to 'q8/dh.c')
-rw-r--r--q8/dh.c38
1 files changed, 38 insertions, 0 deletions
diff --git a/q8/dh.c b/q8/dh.c
new file mode 100644
index 0000000..074dfc7
--- /dev/null
+++ b/q8/dh.c
@@ -0,0 +1,38 @@
1#include <stdio.h>
2#include <stdlib.h>
3#include <time.h>
4
5// Function to compute a^m mod n
6int compute(int a, int m, int n) {
7 int r;
8 int y = 1;
9
10 while (m > 0) {
11 r = m % 2;
12 if (r == 1)
13 y = (y * a) % n;
14 a = a * a % n;
15
16 m = m / 2;
17 }
18
19 return y;
20}
21
22// C program to demonstrate Diffie-Hellman algorithm
23int main() {
24 int p = 23; // modulus
25 int g = 5; // base
26 int a, b; // a - Alice's Secret Key, b - Bob's Secret Key.
27 int A, B; // A - Alice's Public Key, B - Bob's Public Key
28 srand(time(0));
29 a = rand(); // or use rand()
30 A = compute(g, a, p);
31 srand(time(0));
32 b = rand(); // or use rand()
33 B = compute(g, b, p);
34 int keyA = compute(B, a, p);
35 int keyB = compute(A, b, p);
36 printf("\nAlice's Secret Key is %d\nBob's Secret Key is %d\n\n", keyA, keyB);
37 return 0;
38}