Reputation: 899
I am trying to implement RSA key signing and verifying. I am making use of the modular exponentiation where I am encountering errors possibly due to integer overflow.
uint64_t modmult(uint64_t a,uint64_t b,uint64_t mod)
{
if (a == 0 || b < mod / a)
return ((uint64_t)a*b)%mod;
uint64_t sum;
sum = 0;
while(b>0)
{
if(b&1)
sum = (sum + a) % mod;
a = (2*a) % mod;
b>>=1;
}
return sum;
}
uint64_t modpow( uint64_t a,uint64_t b,uint64_t mod)
{
uint64_t product,pseq;
product=1;
pseq=a%mod;
while(b>0)
{
if(b&1)
product=modmult(product,pseq,mod);
pseq=modmult(pseq,pseq,mod);
b>>=1;
}
return product;
}
The function call
long long d = 2897297195663230443;
uint64_t n = 10136926879504331723;
modpow(1233,d,n);
The n
is a multiple of two unsigned uint32_t prime numbers (4063800743,2494444861)
the modular exponentiation
the result is 3148683887780272464
, but it should be 9640529604970470922
Basically, this implementation is not handling unsigned 64 integer values of n
well
Upvotes: 0
Views: 318
Reputation: 126110
The problem is that, due to the modulus being > 263, the a + sum
step in your modmult
routine might overflow, losing a bit. The same might happen with 2*a
.
One way to fix the problem would be to add a modadd
routine:
uint64_t modadd(uint_64_t a, uint64_t b, uint64_t mod) {
if (a >= mod) a %= mod; // precondition -- might not be needed if the caller can guarentee it.
if (b >= mod) b %= mod; // precondition -- might not be needed if the caller can guarentee it
a += b;
if (a >= mod || a < b) a -= mod;
return a;
}
Then, use modadd(sum, a, mod)
and modadd(a, a, mod)
in your modmult
routine.
Upvotes: 2