Skip to content

Instantly share code, notes, and snippets.

@cicorias
Forked from ofaurax/modinverse.py
Created October 25, 2021 19:56
Show Gist options
  • Save cicorias/1a05d976e6d4db1967616a15d9cebe96 to your computer and use it in GitHub Desktop.
Save cicorias/1a05d976e6d4db1967616a15d9cebe96 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)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment