Skip to content

Instantly share code, notes, and snippets.

@ofaurax
Created March 30, 2016 15:04
Show Gist options
  • Save ofaurax/6103869014c246f962ab30a513fb5b49 to your computer and use it in GitHub Desktop.
Save ofaurax/6103869014c246f962ab30a513fb5b49 to your computer and use it in GitHub Desktop.
Modular Inverse for RSA in python
#!/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)
@WightmanC
Copy link

Struggled with the "d" this makes it so simple.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment