Skip to content

Commit

Permalink
RSA private exponentiation: multiply blinding invert in Mont
Browse files Browse the repository at this point in the history
When blinding, multiply result of exponentiation my blinding invert in
Montgomery form to make code more constant time.
  • Loading branch information
SparkiDev committed Nov 17, 2023
1 parent 1a3f3aa commit d3448e2
Show file tree
Hide file tree
Showing 6 changed files with 269 additions and 150 deletions.
33 changes: 29 additions & 4 deletions wolfcrypt/src/rsa.c
Original file line number Diff line number Diff line change
Expand Up @@ -2495,6 +2495,7 @@ static int RsaFunctionPrivate(mp_int* tmp, RsaKey* key, WC_RNG* rng)
{
int ret = 0;
#if defined(WC_RSA_BLINDING) && !defined(WC_NO_RNG)
mp_digit mp;
DECL_MP_INT_SIZE_DYN(rnd, mp_bitsused(&key->n), RSA_MAX_SIZE);
DECL_MP_INT_SIZE_DYN(rndi, mp_bitsused(&key->n), RSA_MAX_SIZE);
#endif /* WC_RSA_BLINDING && !WC_NO_RNG */
Expand Down Expand Up @@ -2627,9 +2628,31 @@ static int RsaFunctionPrivate(mp_int* tmp, RsaKey* key, WC_RNG* rng)
#endif /* RSA_LOW_MEM */

#if defined(WC_RSA_BLINDING) && !defined(WC_NO_RNG)
/* unblind */
if (ret == 0 && mp_mulmod(tmp, rndi, &key->n, tmp) != MP_OKAY)
/* Multiply result (tmp) by bliding invertor (rndi).
* Use Montogemery form to make operation more constant time.
*/
if ((ret == 0) && (mp_montgomery_setup(&key->n, &mp) != MP_OKAY)) {
ret = MP_MULMOD_E;
}
if ((ret == 0) && (mp_montgomery_calc_normalization(rnd, &key->n) !=
MP_OKAY)) {
ret = MP_MULMOD_E;
}
/* Convert blinding invert to Montogmery form. */
if ((ret == 0) && (mp_mul(rndi, rnd, rndi) != MP_OKAY)) {
ret = MP_MULMOD_E;
}
if ((ret == 0) && (mp_mod(rndi, &key->n, rndi) != MP_OKAY)) {
ret = MP_MULMOD_E;
}
/* Multiply result by blinding invert. */
if ((ret == 0) && (mp_mul(tmp, rndi, tmp) != MP_OKAY)) {
ret = MP_MULMOD_E;
}
/* Reduce result. */
if ((ret == 0) && (mp_montgomery_reduce_ct(tmp, &key->n, mp) != MP_OKAY)) {
ret = MP_MULMOD_E;
}

mp_forcezero(rndi);
mp_forcezero(rnd);
Expand Down Expand Up @@ -3520,8 +3543,9 @@ static int RsaPrivateDecryptEx(const byte* in, word32 inLen, byte* out,
mgf, label, labelSz, saltLen,
mp_count_bits(&key->n), key->heap);
#endif
if (rsa_type == RSA_PUBLIC_DECRYPT && ret > (int)outLen)
if (rsa_type == RSA_PUBLIC_DECRYPT && ret > (int)outLen) {
ret = RSA_BUFFER_E;
}
else if (ret >= 0 && pad != NULL) {
/* only copy output if not inline */
if (outPtr == NULL) {
Expand All @@ -3547,8 +3571,9 @@ static int RsaPrivateDecryptEx(const byte* in, word32 inLen, byte* out,
XMEMCPY(out, pad, (size_t)ret);
}
}
else
else {
*outPtr = pad;
}

#if !defined(WOLFSSL_RSA_VERIFY_ONLY)
ret = ctMaskSelInt(ctMaskLTE(ret, (int)outLen), ret, RSA_BUFFER_E);
Expand Down
Loading

0 comments on commit d3448e2

Please sign in to comment.