Skip to content

Commit 61a2d2d

Browse files
Merge pull request #6955 from SparkiDev/rsa_dec_inv_blind_mul_mont
RSA private exponentiation: multiply blinding invert in Mont
2 parents a111c5b + d3448e2 commit 61a2d2d

6 files changed

Lines changed: 269 additions & 150 deletions

File tree

wolfcrypt/src/rsa.c

Lines changed: 29 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -2495,6 +2495,7 @@ static int RsaFunctionPrivate(mp_int* tmp, RsaKey* key, WC_RNG* rng)
24952495
{
24962496
int ret = 0;
24972497
#if defined(WC_RSA_BLINDING) && !defined(WC_NO_RNG)
2498+
mp_digit mp;
24982499
DECL_MP_INT_SIZE_DYN(rnd, mp_bitsused(&key->n), RSA_MAX_SIZE);
24992500
DECL_MP_INT_SIZE_DYN(rndi, mp_bitsused(&key->n), RSA_MAX_SIZE);
25002501
#endif /* WC_RSA_BLINDING && !WC_NO_RNG */
@@ -2627,9 +2628,31 @@ static int RsaFunctionPrivate(mp_int* tmp, RsaKey* key, WC_RNG* rng)
26272628
#endif /* RSA_LOW_MEM */
26282629

26292630
#if defined(WC_RSA_BLINDING) && !defined(WC_NO_RNG)
2630-
/* unblind */
2631-
if (ret == 0 && mp_mulmod(tmp, rndi, &key->n, tmp) != MP_OKAY)
2631+
/* Multiply result (tmp) by bliding invertor (rndi).
2632+
* Use Montogemery form to make operation more constant time.
2633+
*/
2634+
if ((ret == 0) && (mp_montgomery_setup(&key->n, &mp) != MP_OKAY)) {
2635+
ret = MP_MULMOD_E;
2636+
}
2637+
if ((ret == 0) && (mp_montgomery_calc_normalization(rnd, &key->n) !=
2638+
MP_OKAY)) {
2639+
ret = MP_MULMOD_E;
2640+
}
2641+
/* Convert blinding invert to Montogmery form. */
2642+
if ((ret == 0) && (mp_mul(rndi, rnd, rndi) != MP_OKAY)) {
2643+
ret = MP_MULMOD_E;
2644+
}
2645+
if ((ret == 0) && (mp_mod(rndi, &key->n, rndi) != MP_OKAY)) {
26322646
ret = MP_MULMOD_E;
2647+
}
2648+
/* Multiply result by blinding invert. */
2649+
if ((ret == 0) && (mp_mul(tmp, rndi, tmp) != MP_OKAY)) {
2650+
ret = MP_MULMOD_E;
2651+
}
2652+
/* Reduce result. */
2653+
if ((ret == 0) && (mp_montgomery_reduce_ct(tmp, &key->n, mp) != MP_OKAY)) {
2654+
ret = MP_MULMOD_E;
2655+
}
26332656

26342657
mp_forcezero(rndi);
26352658
mp_forcezero(rnd);
@@ -3520,8 +3543,9 @@ static int RsaPrivateDecryptEx(const byte* in, word32 inLen, byte* out,
35203543
mgf, label, labelSz, saltLen,
35213544
mp_count_bits(&key->n), key->heap);
35223545
#endif
3523-
if (rsa_type == RSA_PUBLIC_DECRYPT && ret > (int)outLen)
3546+
if (rsa_type == RSA_PUBLIC_DECRYPT && ret > (int)outLen) {
35243547
ret = RSA_BUFFER_E;
3548+
}
35253549
else if (ret >= 0 && pad != NULL) {
35263550
/* only copy output if not inline */
35273551
if (outPtr == NULL) {
@@ -3547,8 +3571,9 @@ static int RsaPrivateDecryptEx(const byte* in, word32 inLen, byte* out,
35473571
XMEMCPY(out, pad, (size_t)ret);
35483572
}
35493573
}
3550-
else
3574+
else {
35513575
*outPtr = pad;
3576+
}
35523577

35533578
#if !defined(WOLFSSL_RSA_VERIFY_ONLY)
35543579
ret = ctMaskSelInt(ctMaskLTE(ret, (int)outLen), ret, RSA_BUFFER_E);

0 commit comments

Comments
 (0)