12 MP_INT p
,g
; /* prime modulus and generator */
15 static string_t
dh_makepublic(void *sst
, uint8_t *secret
, int32_t secretlen
)
19 MP_INT a
, b
; /* a is secret key, b is public key */
24 read_mpbin(&a
, secret
, secretlen
);
26 mpz_powm(&b
, &st
->g
, &a
, &st
->p
);
35 static dh_makeshared_fn dh_makeshared
;
36 static void dh_makeshared(void *sst
, uint8_t *secret
, int32_t secretlen
,
37 cstring_t rempublic
, uint8_t *sharedsecret
,
47 read_mpbin(&a
, secret
, secretlen
);
48 mpz_set_str(&b
, rempublic
, 16);
50 mpz_powm(&c
, &b
, &a
, &st
->p
);
52 write_mpbin(&c
,sharedsecret
,buflen
);
59 static list_t
*dh_apply(closure_t
*self
, struct cloc loc
, dict_t
*context
,
66 st
=safe_malloc(sizeof(*st
),"dh_apply");
67 st
->cl
.description
="dh";
70 st
->cl
.interface
=&st
->ops
;
72 st
->ops
.makepublic
=dh_makepublic
;
73 st
->ops
.makeshared
=dh_makeshared
;
75 /* We have two string arguments: the first is the modulus, and the
76 second is the generator. Both are in hex. */
79 if (i
->type
!=t_string
) {
80 cfgfatal(i
->loc
,"diffie-hellman","first argument must be a "
84 if (mpz_init_set_str(&st
->p
,p
,16)!=0) {
85 cfgfatal(i
->loc
,"diffie-hellman","\"%s\" is not a hex number "
89 cfgfatal(loc
,"diffie-hellman","you must provide a prime modulus\n");
94 if (i
->type
!=t_string
) {
95 cfgfatal(i
->loc
,"diffie-hellman","second argument must be a "
99 if (mpz_init_set_str(&st
->g
,g
,16)!=0) {
100 cfgfatal(i
->loc
,"diffie-hellman","\"%s\" is not a hex number "
104 cfgfatal(loc
,"diffie-hellman","you must provide a generator\n");
108 if (i
&& i
->type
==t_bool
&& i
->data
.bool==False
) {
109 Message(M_INFO
,"diffie-hellman (%s:%d): skipping modulus "
110 "primality check\n",loc
.file
,loc
.line
);
112 /* Test that the modulus is really prime */
113 if (mpz_probab_prime_p(&st
->p
,5)==0) {
114 cfgfatal(loc
,"diffie-hellman","modulus must be a prime\n");
118 size_t sz
=mpz_sizeinbase(&st
->p
,2)/8;
120 cfgfatal(loc
,"diffie-hellman","modulus far too large\n");
122 if (mpz_cmp(&st
->g
,&st
->p
) >= 0) {
123 cfgfatal(loc
,"diffie-hellman","generator must be less than modulus\n");
128 return new_closure(&st
->cl
);
131 void dh_module(dict_t
*dict
)
133 add_closure(dict
,"diffie-hellman",dh_apply
);