Skip to content

Instantly share code, notes, and snippets.

@juanplopes
Created March 4, 2012 21:41
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save juanplopes/1974922 to your computer and use it in GitHub Desktop.
Save juanplopes/1974922 to your computer and use it in GitHub Desktop.
Simple RSA impl (revisited)
def gcd(a,b):
if b==0: return (1, 0)
q = a/b
x,y = gcd(b, a-q*b)
return (y, x-q*y)
def inverse(a, b):
x,y = gcd(a,b)
return (x if x > 0 else x+b)
p,q = 41, 47 #primes
n,phi = p*q, (p-1)*(q-1) #modulus and totient
e,d = 7, inverse(7,phi) #public and private exponents
plain = 42
ciphered = pow(plain, e, n)
plain_again = pow(ciphered, d, n)
print 'Public key:', (n,e)
print 'Private key:', (n,d)
print 'Message:', plain, '->', ciphered, '->', plain_again
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment