I want to calculate ab mod n for use in RSA decryption. My code (below) returns incorrect answers. What is wrong with it?
unsigned long int decrypt2(int a,int b,int n)
{
unsigned long int res = 1;
for (int i = 0; i < (b / 2); i++)
{
res *= ((a * a) % n);
res %= n;
}
if (b % n == 1)
res *=a;
res %=n;
return res;
}
You can try this C++ code. I’ve used it with 32 and 64-bit integers. I’m sure I got this from SO.
You can find this algorithm and related discussion in the literature on p. 244 of
Note that the multiplications
result * baseandbase * baseare subject to overflow in this simplified version. If the modulus is more than half the width ofT(i.e. more than the square root of the maximumTvalue), then one should use a suitable modular multiplication algorithm instead – see the answers to Ways to do modulo multiplication with primitive types.