From 1afc0df83d0aa2e52656d94c20c772a86a233d50 Mon Sep 17 00:00:00 2001 From: jordan Date: Fri, 14 Jul 2023 13:57:29 -0500 Subject: [PATCH 1/2] tfm fp_exptmod_nct: set result to zero when base is zero --- wolfcrypt/src/tfm.c | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/wolfcrypt/src/tfm.c b/wolfcrypt/src/tfm.c index 4a4c148c73..618d532e1d 100644 --- a/wolfcrypt/src/tfm.c +++ b/wolfcrypt/src/tfm.c @@ -3171,8 +3171,10 @@ int fp_exptmod_nct(fp_int * G, fp_int * X, fp_int * P, fp_int * Y) int x = fp_count_bits (X); #endif + /* 0^X mod P = 0 mod P = 0. + * Set result to 0 and return early. */ if (fp_iszero(G)) { - fp_set(G, 0); + fp_set(Y, 0); return FP_OKAY; } From df58c4dea77f0f173a4d86cd538c1ec8dc05a54c Mon Sep 17 00:00:00 2001 From: jordan Date: Sat, 15 Jul 2023 10:00:50 -0500 Subject: [PATCH 2/2] tfm fp_exptmod_nct: handle special cases better --- wolfcrypt/src/tfm.c | 19 ++++++++++++------- 1 file changed, 12 insertions(+), 7 deletions(-) diff --git a/wolfcrypt/src/tfm.c b/wolfcrypt/src/tfm.c index 618d532e1d..cceb6801d6 100644 --- a/wolfcrypt/src/tfm.c +++ b/wolfcrypt/src/tfm.c @@ -3171,16 +3171,21 @@ int fp_exptmod_nct(fp_int * G, fp_int * X, fp_int * P, fp_int * Y) int x = fp_count_bits (X); #endif - /* 0^X mod P = 0 mod P = 0. - * Set result to 0 and return early. */ - if (fp_iszero(G)) { + /* handle modulus of zero and prevent overflows */ + if (fp_iszero(P) || (P->used > (FP_SIZE/2))) { + return FP_VAL; + } + if (fp_isone(P)) { fp_set(Y, 0); return FP_OKAY; } - - /* prevent overflows */ - if (P->used > (FP_SIZE/2)) { - return FP_VAL; + if (fp_iszero(X)) { + fp_set(Y, 1); + return FP_OKAY; + } + if (fp_iszero(G)) { + fp_set(Y, 0); + return FP_OKAY; } #if defined(WOLFSSL_ESP32_CRYPT_RSA_PRI) && \