aboutsummaryrefslogtreecommitdiff
path: root/q8/dh.c
diff options
context:
space:
mode:
Diffstat (limited to 'q8/dh.c')
-rw-r--r--q8/dh.c34
1 files changed, 24 insertions, 10 deletions
diff --git a/q8/dh.c b/q8/dh.c
index 074dfc7..1c70c8a 100644
--- a/q8/dh.c
+++ b/q8/dh.c
@@ -2,7 +2,7 @@
2#include <stdlib.h> 2#include <stdlib.h>
3#include <time.h> 3#include <time.h>
4 4
5// Function to compute a^m mod n 5
6int compute(int a, int m, int n) { 6int compute(int a, int m, int n) {
7 int r; 7 int r;
8 int y = 1; 8 int y = 1;
@@ -12,27 +12,41 @@ int compute(int a, int m, int n) {
12 if (r == 1) 12 if (r == 1)
13 y = (y * a) % n; 13 y = (y * a) % n;
14 a = a * a % n; 14 a = a * a % n;
15
16 m = m / 2; 15 m = m / 2;
17 } 16 }
18 17
19 return y; 18 return y;
20} 19}
21 20
22// C program to demonstrate Diffie-Hellman algorithm 21int rand_range(int l, int u) {
22 return rand() % (u - l + 1) + l;
23}
24
25
23int main() { 26int main() {
24 int p = 23; // modulus 27 int p = 23;
25 int g = 5; // base 28 int g = 5;
26 int a, b; // a - Alice's Secret Key, b - Bob's Secret Key. 29
27 int A, B; // A - Alice's Public Key, B - Bob's Public Key 30 printf("Modulus: %d, Base: %d\n\n", p, g);
31 int a, b;
32 int A, B;
33
34 int l = 1, u = 1000;
35 printf("RNG range: %d - %d\n\n", l, u);
36
28 srand(time(0)); 37 srand(time(0));
29 a = rand(); // or use rand() 38 a = rand_range(l,u);
30 A = compute(g, a, p); 39 A = compute(g, a, p);
40
31 srand(time(0)); 41 srand(time(0));
32 b = rand(); // or use rand() 42 b = rand_range(l,u);
33 B = compute(g, b, p); 43 B = compute(g, b, p);
44
34 int keyA = compute(B, a, p); 45 int keyA = compute(B, a, p);
35 int keyB = compute(A, b, p); 46 int keyB = compute(A, b, p);
36 printf("\nAlice's Secret Key is %d\nBob's Secret Key is %d\n\n", keyA, keyB); 47
48 printf("Alice's Secret is %d\nBob's Secret is %d\n\n", a, b);
49 printf("Alice's Public Key is %d\nBob's Public Key is %d\n\n", A, B);
50 printf("Alice's Secret Key is %d\nBob's Secret Key is %d\n\n", keyA, keyB);
37 return 0; 51 return 0;
38} 52}