From 0cc50521b6f5aa47b5c9d224a2c22ebd06af1c60 Mon Sep 17 00:00:00 2001 From: Sean Parkinson Date: Fri, 21 Apr 2023 11:23:47 +1000 Subject: [PATCH] ECC: max bits for a key must handle order as well The order may be 1 bit larger than prime for some curves. Handle this in calculation of maximum size of curve. SP int _sp_mont_red(): ensure m->used is never 0 when doing default implementaion. --- wolfcrypt/src/ecc.c | 12 ++++++++++-- wolfcrypt/src/sp_int.c | 4 ++-- 2 files changed, 12 insertions(+), 4 deletions(-) diff --git a/wolfcrypt/src/ecc.c b/wolfcrypt/src/ecc.c index 99ee7aca2..53eaff4d7 100644 --- a/wolfcrypt/src/ecc.c +++ b/wolfcrypt/src/ecc.c @@ -227,9 +227,17 @@ ECC Curve Sizes: #else #define MAX_ECC_BITS_USE MAX_ECC_BITS_NEEDED #endif +#if !defined(WOLFSSL_CUSTOM_CURVES) && (ECC_MIN_KEY_SZ > 160) && \ + (!defined(HAVE_ECC_KOBLITZ) || (ECC_MIN_KEY_SZ > 224)) #define ECC_KEY_MAX_BITS(key) \ - ((((key) == NULL) || ((key)->dp == NULL)) ? MAX_ECC_BITS_USE \ - : (unsigned)((key)->dp->size * 8)) + ((((key) == NULL) || ((key)->dp == NULL)) ? MAX_ECC_BITS_USE : \ + ((unsigned)((key)->dp->size * 8))) +#else +/* Add one bit for cases when order is a bit greater than prime. */ +#define ECC_KEY_MAX_BITS(key) \ + ((((key) == NULL) || ((key)->dp == NULL)) ? MAX_ECC_BITS_USE : \ + ((unsigned)((key)->dp->size * 8 + 1))) +#endif /* forward declarations */ static int wc_ecc_new_point_ex(ecc_point** point, void* heap); diff --git a/wolfcrypt/src/sp_int.c b/wolfcrypt/src/sp_int.c index 571e3a897..fac64425b 100644 --- a/wolfcrypt/src/sp_int.c +++ b/wolfcrypt/src/sp_int.c @@ -16552,8 +16552,8 @@ static int _sp_mont_red(sp_int* a, const sp_int* m, sp_int_digit mp) a->dp[i] = 0; } - /* Special case when modulus is 1 digit. */ - if (m->used == 1) { + /* Special case when modulus is 1 digit or less. */ + if (m->used <= 1) { /* mu = (mp * DigitMask(a, i)) & WORD_MASK */ mu = mp * a->dp[0]; /* a += mu * m */