aboutsummaryrefslogtreecommitdiff
path: root/q8/dh.c
blob: 1c70c8a944f001ef53f0d436e8497854ec5d345d (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
#include <stdio.h>
#include <stdlib.h>
#include <time.h>


int compute(int a, int m, int n) {
  int r;
  int y = 1;

  while (m > 0) {
    r = m % 2;
    if (r == 1)
      y = (y * a) % n;
    a = a * a % n;
    m = m / 2;
  }

  return y;
}

int rand_range(int l, int u) {
    return rand() % (u - l + 1) + l;
}


int main() {
  int p = 23;
  int g = 5; 

  printf("Modulus: %d, Base: %d\n\n", p, g);
  int a, b;
  int A, B;

  int l = 1, u = 1000;
  printf("RNG range: %d - %d\n\n", l, u);

  srand(time(0));
  a = rand_range(l,u);
  A = compute(g, a, p);

  srand(time(0));
  b = rand_range(l,u);
  B = compute(g, b, p);

  int keyA = compute(B, a, p);
  int keyB = compute(A, b, p);

  printf("Alice's Secret is %d\nBob's Secret is %d\n\n", a, b);
  printf("Alice's Public Key is %d\nBob's Public Key is %d\n\n", A, B);
  printf("Alice's Secret Key is %d\nBob's Secret Key is %d\n\n", keyA, keyB);
  return 0;
}