Import release 0.1.13
[secnet] / dh.c
1 #include <stdio.h>
2 #include <gmp.h>
3
4 #include "secnet.h"
5 #include "util.h"
6
7 struct dh {
8 closure_t cl;
9 struct dh_if ops;
10 struct cloc loc;
11 MP_INT p,g; /* prime modulus and generator */
12 };
13
14 static string_t dh_makepublic(void *sst, uint8_t *secret, uint32_t secretlen)
15 {
16 struct dh *st=sst;
17 string_t r;
18 MP_INT a, b; /* a is secret key, b is public key */
19
20 mpz_init(&a);
21 mpz_init(&b);
22
23 read_mpbin(&a, secret, secretlen);
24
25 mpz_powm(&b, &st->g, &a, &st->p);
26
27 r=write_mpstring(&b);
28
29 mpz_clear(&a);
30 mpz_clear(&b);
31 return r;
32 }
33
34 static void dh_makeshared(void *sst, uint8_t *secret, uint32_t secretlen,
35 string_t rempublic, uint8_t *sharedsecret,
36 uint32_t buflen)
37 {
38 struct dh *st=sst;
39 MP_INT a, b, c;
40
41 mpz_init(&a);
42 mpz_init(&b);
43 mpz_init(&c);
44
45 read_mpbin(&a, secret, secretlen);
46 mpz_set_str(&b, rempublic, 16);
47
48 mpz_powm(&c, &b, &a, &st->p);
49
50 write_mpbin(&c,sharedsecret,buflen);
51
52 mpz_clear(&a);
53 mpz_clear(&b);
54 mpz_clear(&c);
55 }
56
57 static list_t *dh_apply(closure_t *self, struct cloc loc, dict_t *context,
58 list_t *args)
59 {
60 struct dh *st;
61 string_t p,g;
62 item_t *i;
63
64 st=safe_malloc(sizeof(*st),"dh_apply");
65 st->cl.description="dh";
66 st->cl.type=CL_DH;
67 st->cl.apply=NULL;
68 st->cl.interface=&st->ops;
69 st->ops.st=st;
70 st->ops.makepublic=dh_makepublic;
71 st->ops.makeshared=dh_makeshared;
72 st->loc=loc;
73 /* We have two string arguments: the first is the modulus, and the
74 second is the generator. Both are in hex. */
75 i=list_elem(args,0);
76 if (i) {
77 if (i->type!=t_string) {
78 cfgfatal(i->loc,"diffie-hellman","first argument must be a "
79 "string\n");
80 }
81 p=i->data.string;
82 if (mpz_init_set_str(&st->p,p,16)!=0) {
83 cfgfatal(i->loc,"diffie-hellman","\"%s\" is not a hex number "
84 "string\n",p);
85 }
86 } else {
87 cfgfatal(loc,"diffie-hellman","you must provide a prime modulus\n");
88 }
89
90 i=list_elem(args,1);
91 if (i) {
92 if (i->type!=t_string) {
93 cfgfatal(i->loc,"diffie-hellman","second argument must be a "
94 "string\n");
95 }
96 g=i->data.string;
97 if (mpz_init_set_str(&st->g,g,16)!=0) {
98 cfgfatal(i->loc,"diffie-hellman","\"%s\" is not a hex number "
99 "string\n",g);
100 }
101 } else {
102 cfgfatal(loc,"diffie-hellman","you must provide a generator\n");
103 }
104
105 i=list_elem(args,2);
106 if (i && i->type==t_bool && i->data.bool==False) {
107 Message(M_INFO,"diffie-hellman (%s:%d): skipping modulus "
108 "primality check\n",loc.file,loc.line);
109 } else {
110 /* Test that the modulus is really prime */
111 if (mpz_probab_prime_p(&st->p,5)==0) {
112 cfgfatal(loc,"diffie-hellman","modulus must be a prime\n");
113 }
114 }
115 st->ops.len=mpz_sizeinbase(&st->p,2)/8;
116
117 return new_closure(&st->cl);
118 }
119
120 init_module dh_module;
121 void dh_module(dict_t *dict)
122 {
123 add_closure(dict,"diffie-hellman",dh_apply);
124 }