Implementing RSA in Python from Scratch
Quite a bit of that code can be eliminated if you use the 3 argument form of Python’s pow() function.  pow(a, b, n)

efficiently computes  (a ** b) % n

and  pow(a, -1, n)

finds b such that  (a * b) % n == 1