From ad2225deb5b01eb751ba1882c0e9c2fc6b1fcafa Mon Sep 17 00:00:00 2001 From: Frank Denis Date: Mon, 7 Sep 2026 21:03:43 +0200 Subject: [PATCH] crypto.ff: add a function to decode reduced field elements Add fromBytesReduced() to accept values below 2^m.bits() (including values at or above the modulus). --- lib/std/crypto/ff.zig | 15 +++++++++++++++ 1 file changed, 15 insertions(+) diff --git a/lib/std/crypto/ff.zig b/lib/std/crypto/ff.zig index 82a063529942482d271746bade1c7917cfbaf978..42be03564cc4c7262e769a5b6cef06975e392aaa 100644 --- a/lib/std/crypto/ff.zig +++ b/lib/std/crypto/ff.zig @@ -472,6 +472,21 @@ fn Fe_(comptime bits: comptime_int) type { return fe; } + /// Decodes and reduces a byte string whose value is below 2^m.bits(). + pub fn fromBytesReduced(m: Modulus(bits), bytes: []const u8, comptime endian: Endian) OverflowError!Self { + var fe = Self{ .v = FeUint.zero }; + const m_limbs_count = m.limbs_count(); + const fe_limbs = fe.v.limbs()[0..m_limbs_count]; + var acc = decodeBytes(fe_limbs, bytes, endian); + + acc |= math.shr(Limb, fe_limbs[m_limbs_count - 1], t_bits - m.leading); + if (!ct.eql(acc, 0)) return error.Overflow; + fe.v.limbs_len = m_limbs_count; + + _ = fe.v.conditionalSubWithOverflow(ct.limbsCmpGeq(fe.v, m.v), m.v); + return fe; + } + /// Converts the field element to a byte string. /// Returns an error if the element is in Montgomery form. pub fn toBytes(self: Self, bytes: []u8, comptime endian: Endian) (OverflowError || RepresentationError)!void { -- 2.54.0