From 7226aee256fae278f07edb49f97ffa8074036830 Mon Sep 17 00:00:00 2001 From: "Kasper S. Nielsen" Date: Tue, 19 May 2026 12:55:09 +0200 Subject: [PATCH] Fix truncate negative numbers --- .../lib/common/math/integer/binary/Truncate.java | 15 ++++++--------- 1 file changed, 6 insertions(+), 9 deletions(-) diff --git a/lib/common/src/main/java/dk/alexandra/fresco/lib/common/math/integer/binary/Truncate.java b/lib/common/src/main/java/dk/alexandra/fresco/lib/common/math/integer/binary/Truncate.java index f0efeb0c4..f4a7136b5 100644 --- a/lib/common/src/main/java/dk/alexandra/fresco/lib/common/math/integer/binary/Truncate.java +++ b/lib/common/src/main/java/dk/alexandra/fresco/lib/common/math/integer/binary/Truncate.java @@ -49,13 +49,15 @@ public DRes buildComputation(ProtocolBuilderNumeric builder) { }).seq((seq, randomAdditiveMask) -> { - DRes result = seq.numeric().add(input, randomAdditiveMask.value); + DRes b = seq.numeric().add(BigInteger.ONE.shiftLeft(maxBitLength - 1), input); + DRes result = seq.numeric().add(b, randomAdditiveMask.value); DRes open = seq.numeric().open(result); return Pair.lazy(open, randomAdditiveMask); }).seq((seq, maskedInput) -> { BigInteger masked = maskedInput.getFirst().out(); + BigInteger maskedPrime = masked.mod(BigInteger.ONE.shiftLeft(shifts)); RandomAdditiveMask mask = maskedInput.getSecond(); /* @@ -66,15 +68,10 @@ public DRes buildComputation(ProtocolBuilderNumeric builder) { BigInteger inverse = BigInteger.ONE.shiftLeft(shifts).modInverse(seq.getBasicNumericContext().getModulus()); - DRes rTop = seq.numeric().sub(mask.value, rBottom); - /* - * rTop is r with the last shifts bits set to zero, and it is hence divisible by 2^shifts, so - * multiplying with the inverse in the field corresponds to shifting. - */ - DRes rShifted = seq.numeric().mult(inverse, rTop); - BigInteger mShifted = masked.shiftRight(shifts); - return seq.numeric().sub(mShifted, rShifted); + DRes aPrime = seq.numeric().sub(maskedPrime, rBottom); + DRes d = seq.numeric().sub(input, aPrime); + return seq.numeric().mult(inverse, d); }); } }