Skip to content

Commit

Permalink
Merge pull request #8335 from douzzer/20250106-_DhSetKey-FFDHE-short-…
Browse files Browse the repository at this point in the history
…circuit

20250106-_DhSetKey-FFDHE-short-circuit
  • Loading branch information
dgarske authored Jan 7, 2025
2 parents d2ea3c6 + fffafe6 commit 4a12351
Show file tree
Hide file tree
Showing 2 changed files with 46 additions and 6 deletions.
42 changes: 39 additions & 3 deletions wolfcrypt/src/dh.c
Original file line number Diff line number Diff line change
Expand Up @@ -2544,10 +2544,46 @@ static int _DhSetKey(DhKey* key, const byte* p, word32 pSz, const byte* g,

if (ret == 0 && !trusted) {
int isPrime = 0;
if (rng != NULL)
ret = mp_prime_is_prime_ex(keyP, 8, &isPrime, rng);

/* Short-circuit the primality check for p if it is one of the named
* public moduli (known primes) from RFC 7919.
*/
#ifdef HAVE_FFDHE_2048
if ((pSz == sizeof(dh_ffdhe2048_p)) && (XMEMCMP(p, dh_ffdhe2048_p, sizeof(dh_ffdhe2048_p)) == 0)) {
isPrime = 1;
}
else
#endif
#ifdef HAVE_FFDHE_3072
if ((pSz == sizeof(dh_ffdhe3072_p)) && (XMEMCMP(p, dh_ffdhe3072_p, sizeof(dh_ffdhe3072_p)) == 0)) {
isPrime = 1;
}
else
#endif
#ifdef HAVE_FFDHE_4096
if ((pSz == sizeof(dh_ffdhe4096_p)) && (XMEMCMP(p, dh_ffdhe4096_p, sizeof(dh_ffdhe4096_p)) == 0)) {
isPrime = 1;
}
else
ret = mp_prime_is_prime(keyP, 8, &isPrime);
#endif
#ifdef HAVE_FFDHE_6144
if ((pSz == sizeof(dh_ffdhe6144_p)) && (XMEMCMP(p, dh_ffdhe6144_p, sizeof(dh_ffdhe6144_p)) == 0)) {
isPrime = 1;
}
else
#endif
#ifdef HAVE_FFDHE_8192
if ((pSz == sizeof(dh_ffdhe8192_p)) && (XMEMCMP(p, dh_ffdhe8192_p, sizeof(dh_ffdhe8192_p)) == 0)) {
isPrime = 1;
}
else
#endif
{
if (rng != NULL)
ret = mp_prime_is_prime_ex(keyP, 8, &isPrime, rng);
else
ret = mp_prime_is_prime(keyP, 8, &isPrime);
}

if (ret == 0 && isPrime == 0)
ret = DH_CHECK_PUB_E;
Expand Down
10 changes: 7 additions & 3 deletions wolfcrypt/test/test.c
Original file line number Diff line number Diff line change
Expand Up @@ -22714,16 +22714,20 @@ static wc_test_ret_t dh_ffdhe_test(WC_RNG *rng, int name)
ERROR_OUT(WC_TEST_RET_ENC_EC(ret), done);

#ifdef HAVE_PUBLIC_FFDHE
ret = wc_DhSetKey(key, params->p, params->p_len, params->g, params->g_len);
/* use wc_DhSetKey_ex(), not wc_DhSetKey(), so that trusted=0 is passed to
* _DhSetKey(), exercising the primality check on the modulus:
*/
ret = wc_DhSetKey_ex(key, params->p, params->p_len, params->g,
params->g_len, NULL /* q */, 0 /* qSz */);
#else
ret = wc_DhSetNamedKey(key, name);
#endif
if (ret != 0)
ERROR_OUT(WC_TEST_RET_ENC_EC(ret), done);

#ifdef HAVE_PUBLIC_FFDHE
ret = wc_DhSetKey(key2, params->p, params->p_len, params->g,
params->g_len);
ret = wc_DhSetKey_ex(key2, params->p, params->p_len, params->g,
params->g_len, NULL /* q */, 0 /* qSz */);
#else
ret = wc_DhSetNamedKey(key2, name);
#endif
Expand Down

0 comments on commit 4a12351

Please sign in to comment.