I am found a python script to perform Modular Inverse for RSA in python. However, I am unable to understand on how does the modular inverse in python work. Could you please kindly explain and elaborate on especially modinv and egcd Please kindly comment the the code for more understanding.
Here is the python code sample from this link, https://gist.github.com/ofaurax/6103869014c246f962ab30a513fb5b49
#!/usr/bin/env python3
p = 61
q = 53
n = p*q
phi = (p-1)*(q-1)
# Took from SO
def egcd(a, b):
if a == 0:
return (b, 0, 1)
g, y, x = egcd(b%a,a)
return (g, x - (b//a) * y, y)
def modinv(a, m):
g, x, y = egcd(a, m)
if g != 1:
raise Exception('No modular inverse')
return x%m
e = 17
d = modinv(e, phi)
print('P =', p)
print('Q =', q)
print('N =', n)
print('Phi =', phi)
print('E =', e)
print('D =', d)
print('(E*D)%Phi =', (e*d)%phi)
Thank you