use rand_bn_range() where possible

This commit is contained in:
Steffen Jaeckel 2017-06-28 20:50:21 +02:00
parent bdfecc5f3c
commit d1ecd82a42
3 changed files with 13 additions and 18 deletions

View File

@ -51,7 +51,7 @@ cleanup:
}
/**
Generate a random number N in a range: 0 <= N < limit
Generate a random number N in a range: 1 <= N < limit
*/
int rand_bn_range(void *N, void *limit, prng_state *prng, int wprng)
{
@ -63,7 +63,7 @@ int rand_bn_range(void *N, void *limit, prng_state *prng, int wprng)
do {
res = rand_bn_bits(N, mp_count_bits(limit), prng, wprng);
if (res != CRYPT_OK) return res;
} while (mp_cmp(N, limit) != LTC_MP_LT);
} while (mp_cmp_d(N, 0) != LTC_MP_GT || mp_cmp(N, limit) != LTC_MP_LT);
return CRYPT_OK;
}

View File

@ -35,7 +35,7 @@ int dsa_encrypt_key(const unsigned char *in, unsigned long inlen,
unsigned char *expt, *skey;
void *g_pub, *g_priv;
unsigned long x, y;
int err, qbits;
int err;
LTC_ARGCHK(in != NULL);
LTC_ARGCHK(out != NULL);
@ -73,14 +73,12 @@ int dsa_encrypt_key(const unsigned char *in, unsigned long inlen,
return CRYPT_MEM;
}
/* make a random g_priv, g_pub = g^x pair */
qbits = mp_count_bits(key->q);
do {
if ((err = rand_bn_bits(g_priv, qbits, prng, wprng)) != CRYPT_OK) {
goto LBL_ERR;
}
/* private key x should be from range: 1 <= x <= q-1 (see FIPS 186-4 B.1.2) */
} while (mp_cmp_d(g_priv, 0) != LTC_MP_GT || mp_cmp(g_priv, key->q) != LTC_MP_LT);
/* make a random g_priv, g_pub = g^x pair
private key x should be in range: 1 <= x <= q-1 (see FIPS 186-4 B.1.2)
*/
if ((err = rand_bn_range(g_priv, key->q, prng, wprng)) != CRYPT_OK) {
goto LBL_ERR;
}
/* compute y */
if ((err = mp_exptmod(key->g, g_priv, key->p, g_pub)) != CRYPT_OK) {

View File

@ -24,7 +24,7 @@
*/
int dsa_make_key_ex(prng_state *prng, int wprng, dsa_key *key)
{
int err, qbits;
int err;
LTC_ARGCHK(key != NULL);
LTC_ARGCHK(key->x != NULL);
@ -37,12 +37,9 @@ int dsa_make_key_ex(prng_state *prng, int wprng, dsa_key *key)
/* so now we have our DH structure, generator g, order q, modulus p
Now we need a random exponent [mod q] and it's power g^x mod p
*/
qbits = mp_count_bits(key->q);
do {
if ((err = rand_bn_bits(key->x, qbits, prng, wprng)) != CRYPT_OK) { return err; }
/* private key x should be from range: 1 <= x <= q-1 (see FIPS 186-4 B.1.2) */
} while (mp_cmp_d(key->x, 0) != LTC_MP_GT || mp_cmp(key->x, key->q) != LTC_MP_LT);
if ((err = mp_exptmod(key->g, key->x, key->p, key->y)) != CRYPT_OK) { return err; }
/* private key x should be from range: 1 <= x <= q-1 (see FIPS 186-4 B.1.2) */
if ((err = rand_bn_range(key->x, key->q, prng, wprng)) != CRYPT_OK) { return err; }
if ((err = mp_exptmod(key->g, key->x, key->p, key->y)) != CRYPT_OK) { return err; }
key->type = PK_PRIVATE;
return CRYPT_OK;