0

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
President James K. Polk
  • 40,516
  • 21
  • 95
  • 125
Ivan Gorin
  • 303
  • 2
  • 12

1 Answers1

1

The question was answered by James K Polk, I just had to add this to the extended Euclidean algorithm code:

if t < 0:
    t += n
Ivan Gorin
  • 303
  • 2
  • 12