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.<p><pre><code>  pow(a, b, n)
</code></pre>
efficiently computes<p><pre><code>  (a ** b) % n
</code></pre>
and<p><pre><code>  pow(a, -1, n)
</code></pre>
finds b such that<p><pre><code>  (a * b) % n == 1</code></pre>