From d8d2aa9af438bffa643aabb180011f275afd87d3 Mon Sep 17 00:00:00 2001 From: Frank Denis <124872+jedisct1@users.noreply.github.com> Date: Sun, 2 Mar 2025 11:27:04 +0100 Subject: [PATCH] crypto.pcurves.common: generalize invert() (#23039) The Bernstein-Yang inversion code was meant to be used only with the fields we currently use for the NIST curves. But people copied that code and were confused that it didn't work as expected with other field sizes. It doesn't cost anything to make it work with other field sizes, that may support in the future. So let's do it. This also reduces the diff with the example zig code in fiat crypto. Suggested by @Rexicon226 -- Thank you! --- lib/std/crypto/pcurves/common.zig | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lib/std/crypto/pcurves/common.zig b/lib/std/crypto/pcurves/common.zig index 1099e11347..2af7c3e8fe 100644 --- a/lib/std/crypto/pcurves/common.zig +++ b/lib/std/crypto/pcurves/common.zig @@ -197,7 +197,7 @@ pub fn Field(comptime params: FieldParams) type { /// Return the inverse of a field element, or 0 if a=0. // Field inversion from https://eprint.iacr.org/2021/549.pdf pub fn invert(a: Fe) Fe { - const iterations = (49 * field_bits + 57) / 17; + const iterations = (49 * field_bits + if (field_bits < 46) 80 else 57) / 17; const Limbs = @TypeOf(a.limbs); const Word = @TypeOf(a.limbs[0]); const XLimbs = [a.limbs.len + 1]Word;