Improve handling of mp_init / mp_clear for DH and DSA after speed-up.

This commit is contained in:
David Garske
2017-01-31 16:42:06 -08:00
parent da5825b94d
commit bced81d234
2 changed files with 31 additions and 25 deletions

View File

@ -51,20 +51,21 @@
void wc_InitDhKey(DhKey* key) void wc_InitDhKey(DhKey* key)
{ {
(void)key; if (key) {
/* TomsFastMath doesn't use memory allocation */ mp_init(&key->p);
#ifndef USE_FAST_MATH mp_init(&key->g);
key->p.dp = NULL; }
key->g.dp = NULL;
#endif
} }
void wc_FreeDhKey(DhKey* key) void wc_FreeDhKey(DhKey* key)
{ {
(void)key; if (key) {
mp_clear(&key->p); #ifndef USE_FAST_MATH
mp_clear(&key->g); mp_clear(&key->p);
mp_clear(&key->g);
#endif
}
} }

View File

@ -52,18 +52,20 @@ enum {
void wc_InitDsaKey(DsaKey* key) void wc_InitDsaKey(DsaKey* key)
{ {
if (key == NULL)
return;
key->type = -1; /* haven't decided yet */ key->type = -1; /* haven't decided yet */
key->heap = NULL; key->heap = NULL;
/* TomsFastMath doesn't use memory allocation */ /* public alloc parts */
#ifndef USE_FAST_MATH mp_init(&key->p);
key->p.dp = 0; /* public alloc parts */ mp_init(&key->q);
key->q.dp = 0; mp_init(&key->g);
key->g.dp = 0; mp_init(&key->y);
key->y.dp = 0;
key->x.dp = 0; /* private alloc parts */ /* private alloc parts */
#endif mp_init(&key->x);
} }
@ -78,11 +80,14 @@ int wc_InitDsaKey_h(DsaKey* key, void* h)
void wc_FreeDsaKey(DsaKey* key) void wc_FreeDsaKey(DsaKey* key)
{ {
(void)key; if (key == NULL)
/* TomsFastMath doesn't use memory allocation */ return;
#ifndef USE_FAST_MATH
if (key->type == DSA_PRIVATE) if (key->type == DSA_PRIVATE)
mp_clear(&key->x); mp_forcezero(&key->x);
#ifndef USE_FAST_MATH
mp_clear(&key->x);
mp_clear(&key->y); mp_clear(&key->y);
mp_clear(&key->g); mp_clear(&key->g);
mp_clear(&key->q); mp_clear(&key->q);
@ -148,7 +153,7 @@ int wc_MakeDsaKey(WC_RNG *rng, DsaKey *dsa)
} }
dsa->type = DSA_PRIVATE; dsa->type = DSA_PRIVATE;
return MP_OKAY; return MP_OKAY;
} }
@ -356,7 +361,7 @@ int wc_DsaSign(const byte* digest, byte* out, DsaKey* key, WC_RNG* rng)
byte* tmp = out; /* initial output pointer */ byte* tmp = out; /* initial output pointer */
sz = min((int)sizeof(buffer), mp_unsigned_bin_size(&key->q)); sz = min((int)sizeof(buffer), mp_unsigned_bin_size(&key->q));
if (mp_init_multi(&k, &kInv, &r, &s, &H, 0) != MP_OKAY) if (mp_init_multi(&k, &kInv, &r, &s, &H, 0) != MP_OKAY)
return MP_INIT_E; return MP_INIT_E;
@ -370,12 +375,12 @@ int wc_DsaSign(const byte* digest, byte* out, DsaKey* key, WC_RNG* rng)
if (mp_read_unsigned_bin(&k, buffer, sz) != MP_OKAY) if (mp_read_unsigned_bin(&k, buffer, sz) != MP_OKAY)
ret = MP_READ_E; ret = MP_READ_E;
/* k is a random numnber and it should be less than q /* k is a random numnber and it should be less than q
* if k greater than repeat * if k greater than repeat
*/ */
} while (mp_cmp(&k, &key->q) != MP_LT); } while (mp_cmp(&k, &key->q) != MP_LT);
if (ret == 0 && mp_cmp_d(&k, 1) != MP_GT) if (ret == 0 && mp_cmp_d(&k, 1) != MP_GT)
ret = MP_CMP_E; ret = MP_CMP_E;