I am trying to write an RSA code in python3.6 for educational purposes.
The key generation and message encryption work fine, but I have a problem with decryption. As I understand the decryption algorithm is M = Cd mod n, where M is the message, C is the encrypted message (using the public key of the receiver) , d is the private key of the receiver. The problem is when d is negative, which in my experience is very often. I'm using right-to-left algorithm for modular exponentiation, but I don't know how to make it work with negative exponent. Here's my code for m. e.:
def mod_pow(b, e, m):
if m == 1:
return 0
res = 1
b = b % m
while e > 0:
if e % 2 == 1:
res = (res * b) % m
e = e >> 1
b = (b * b) % m
return res