I want to perform the following calculation in Python:
h^r * m mod p
All of the variables in this calculation are extremely large numbers. This formula would work if the numbers weren't as large:
c2 = (pow(pk,r) * m) % p
But because the numbers are so large, this makes my machine hang. So the natural solution is to include the third argument of the pow
function to include the modulus in that calculation. This calculates extremely fast:
pow(pk,r,p)
^ But how can I adapt this formula above to multiply the result of pk^r
by m
before the modulus is accounted for?
The code in the other answer is not correct. It is missing one important part; dividing exp
by 2;
base = 4
exp = 12
mod = 7
m = 8
result = 1
while exp>0:
if exp%2==0:
result = (result*base)%mod
base = (base*base)%mod
exp = exp //2
print((m*result)%mod)
When exp = exp //2
is missing, it will run forever since exp>0
will be correct forever.
We don't advise writing a function yourself if it is in the library. There is already one in Python ( actually the one that you have uses with an optional third parameter);
pow(base, exp, mod)
Parameter | Description |
---|---|
base | A number the base |
exp | A number, the exponent |
mod | Optional. A number, the modulus |
This library already handling this for you with the Montgomery Modular Multiplication technique that is better than standard repeating squaring if the power is not small.
pow(base, exp, mod) * m % mod
Just use it.
Since this is about encryption, we must also say that one needs a secure modular exponentiation against side-channel attacks. GNU/GMP has already mpz_powm_sec for this purposes. You can access this with gmpy2 module.