I developed a simpler inverse function
def privateExponent(p,q,e): totient=(p-1)*(q-1) for k in range(1,e): if (totient*k+1) % e==0: return (totient*k+1)/e return -1
The equation d * e = 1 (total modulo) can be rewritten as d * e = 1 + k * totient (for some value of k), and the program simply looks for the first value of k, which makes the equation divisible by e (public exponent). This will work if e is small (as is usually recommended).
We can move all bignum operations out of a loop to improve its performance.
def privateExponent(p,q,e): totient=(p-1)*(q-1) t_mod_e=totient % e k=0 total=1 while total!=0: k+=1 total=(total+t_mod_e) % e return (k*totient+1)/e
It turns out that for e = 3 we really do not need to search, because the answer is always 2 * ((p-1) * (q-1) +1) / 3
source share