[PATCH 03/14] crypto: ecdsa - Adjust res.x mod n for NIST P521

From: Stefan Berger
Date: Thu Feb 08 2024 - 17:20:09 EST


When res.x >= n then res.x mod n can be calculated by iteratively sub-
tracting n from res.x until n > res.x. For NIST P192/256/384 this is done
in a single subtraction since these curves' 'n' use all the 64bit digits.
This is also significantly faster than a modulo operation. For NIST P521
the same could take multiple subtractions. However, during testing with
varying NIST P521 keys it was never necessary to do any subtraction at all.

Signed-off-by: Stefan Berger <stefanb@xxxxxxxxxxxxx>
---
crypto/ecdsa.c | 4 ++--
1 file changed, 2 insertions(+), 2 deletions(-)

diff --git a/crypto/ecdsa.c b/crypto/ecdsa.c
index 228f675ac2ed..c9b867a9cbb9 100644
--- a/crypto/ecdsa.c
+++ b/crypto/ecdsa.c
@@ -121,8 +121,8 @@ static int _ecdsa_verify(struct ecc_ctx *ctx, const u64 *hash, const u64 *r, con
ecc_point_mult_shamir(&res, u1, &curve->g, u2, &ctx->pub_key, curve);

/* res.x = res.x mod n (if res.x > order) */
- if (unlikely(vli_cmp(res.x, curve->n, ndigits) == 1))
- /* faster alternative for NIST p384, p256 & p192 */
+ while (unlikely(vli_cmp(res.x, curve->n, ndigits) == 1))
+ /* faster alternative for NIST p521, p384, p256 & p192 */
vli_sub(res.x, res.x, curve->n, ndigits);

if (!vli_cmp(res.x, r, ndigits))
--
2.43.0