From d746c01716cd7d8517dae654fe58cb2a88ac314f Mon Sep 17 00:00:00 2001 From: Michiel Visser Date: Thu, 9 Nov 2023 18:49:00 +0100 Subject: [PATCH] LibCrypto: Simplify modular addition and subtraction Instead of building the REDUCE_PRIME constant on the fly from the carry flag, we now simply use the constant in combination with select. This improves the readablility of the functions significantly. --- Userland/Libraries/LibCrypto/Curves/SECP256r1.cpp | 12 ++++-------- 1 file changed, 4 insertions(+), 8 deletions(-) diff --git a/Userland/Libraries/LibCrypto/Curves/SECP256r1.cpp b/Userland/Libraries/LibCrypto/Curves/SECP256r1.cpp index 4731a16718..3f98ee352e 100644 --- a/Userland/Libraries/LibCrypto/Curves/SECP256r1.cpp +++ b/Userland/Libraries/LibCrypto/Curves/SECP256r1.cpp @@ -124,14 +124,12 @@ static constexpr u256 modular_add(u256 const& left, u256 const& right, bool carr u256 output = left.addc(right, carry); // If there is a carry, subtract p by adding 2^256 - p - u64 t = carry; + u256 addend = select(0u, REDUCE_PRIME, carry); carry = false; - u256 addend { u128 { t, -(t << 32) }, u128 { -t, (t << 32) - (t << 1) } }; output = output.addc(addend, carry); // If there is still a carry, subtract p by adding 2^256 - p - t = carry; - addend = { u128 { t, -(t << 32) }, u128 { -t, (t << 32) - (t << 1) } }; + addend = select(0u, REDUCE_PRIME, carry); return output + addend; } @@ -141,14 +139,12 @@ static constexpr u256 modular_sub(u256 const& left, u256 const& right) u256 output = left.subc(right, borrow); // If there is a borrow, add p by subtracting 2^256 - p - u64 t = borrow; + u256 sub = select(0u, REDUCE_PRIME, borrow); borrow = false; - u256 sub { u128 { t, -(t << 32) }, u128 { -t, (t << 32) - (t << 1) } }; output = output.subc(sub, borrow); // If there is still a borrow, add p by subtracting 2^256 - p - t = borrow; - sub = { u128 { t, -(t << 32) }, u128 { -t, (t << 32) - (t << 1) } }; + sub = select(0u, REDUCE_PRIME, borrow); return output - sub; }