mardi 28 août 2018

Modular exponentiation overflows when using multiple of two uint_32 numbers

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 result is 3148683887780272464, but it should be 9640529604970470922

However when n is a multiple of two signed int32_t prime numbers the result is correct.

Aucun commentaire:

Enregistrer un commentaire