Commit b55e8ba6 authored by Robert Ransom's avatar Robert Ransom
Browse files

Remove a conditional branch

This one had no security implications (good thing, or the shift by a
variable number of bits could leak too), but I suspect that if my computer
weren't so fast or this function were called more often, avoiding the
conditional branch would improve performance.
parent 6124f014
Loading
Loading
Loading
Loading
+8 −9
Original line number Diff line number Diff line
@@ -441,21 +441,20 @@ fcontract(u8 *output, limb *input) {

  for (j = 0; j < 2; ++j) {
    for (i = 0; i < 9; ++i) {
      if ((i & 1) == 1) {
      /* This calculation is a time-invariant way to make input[i] positive
         by borrowing from the next-larger limb.
      */
      const int shift = 26 - (i & 1);
      /* shift depends only on the loop counter, so there is no
         side-channel-resistance reason to not use an if statement
         here, but avoiding a conditional branch with
         frequently-changing condition might improve performance.
      */
      const s32 mask = (s32)(input[i]) >> 31;
        const s32 carry = -(((s32)(input[i]) & mask) >> 25);
        input[i] = (s32)(input[i]) + (carry << 25);
        input[i+1] = (s32)(input[i+1]) - carry;
      } else {
        const s32 mask = (s32)(input[i]) >> 31;
        const s32 carry = -(((s32)(input[i]) & mask) >> 26);
        input[i] = (s32)(input[i]) + (carry << 26);
      const s32 carry = -(((s32)(input[i]) & mask) >> shift);
      input[i] = (s32)(input[i]) + (carry << shift);
      input[i+1] = (s32)(input[i+1]) - carry;
    }
    }
    const s32 mask = (s32)(input[9]) >> 31;
    const s32 carry = -(((s32)(input[9]) & mask) >> 25);
    input[9] = (s32)(input[9]) + (carry << 25);