0

I'm trying to implement the SRP Protocol for secure authentication. My problem is that when I have to calculate a ModPow of a negative number, it also returns a negative number. I know it's maybe called the remainder not the modulus but I really have to get the positive modulus to generate the correct hash.

How could I do that?

stomseven
  • 157
  • 1
  • 2
  • 8
  • Why are you calculating the ModPow of a negative number? I don't think SRP ever does that operation. – Craig Gidney Jul 07 '13 at 01:28
  • Because I got a negative number after subtruction. B - k * pow(g, x, N). This is a negative value for me. – stomseven Jul 07 '13 at 02:12
  • You're supposed to add N until it's not negative anymore. 2 o'clock - 3 o'clock is 11 o'clock, not -1 o'clock. You can do result mod N to make sure it's within one addition of N of 0. – Craig Gidney Jul 07 '13 at 03:05

2 Answers2

1

You can add (or subtract) any multiple of the modulus from the result since: r + km = r (mod m)

I assume the result is in: -m < r < 0, so you would simply use r + m.


The proper thing to do, is to find the least non-negative residue of the base, modulo m, prior to exponentiation - i.e., r <- r + m, and then exponentiate.

Brett Hale
  • 21,653
  • 2
  • 61
  • 90
  • And how can I do that? Because I cannot add m to it until it becomes positive, because it's a very big negative number and m is quite small compare to it. – stomseven Jul 07 '13 at 02:26
0

SRP doesn't have any operations where you need to take the ModPow of a negative number. All arithmetic related to ModPow is supposed to be done in modular arithmetic, which in practice means all inputs and outputs should be non-negative and less than some modulus N.

If you're ending up with a negative number, perhaps after doing a subtraction, you're essentially supposed to add N to the result until it's non-negative. For huge negative values, computing x % N is equivalent to adding N until it only requires one more addition of N to be positive.

Craig Gidney
  • 17,763
  • 5
  • 68
  • 136