Advertisement
MrPolywhirl

RSA Encryption

Jun 9th, 2014
417
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.64 KB | None | 0 0
  1. #!/usr/bin/env python
  2.  
  3. ''' Convert to and from ASCII text.
  4. '''
  5. def str_to_ascii(s):
  6.     return [ord(c) for c in s]
  7.  
  8. def ascii_to_str(l):
  9.     return ''.join(chr(x) for x in l)
  10.  
  11. ''' Define math operations.
  12. '''
  13. def pow(x, n):
  14.     r = x
  15.     for i in range(n-1):
  16.         r = r * x
  17.     return r
  18.    
  19. def egcd(a, b):
  20.     x,y, u,v = 0,1, 1,0
  21.     while a != 0:
  22.         q, r = b//a, b%a
  23.         m, n = x-u*q, y-v*q
  24.         b,a, x,y, u,v = a,r, u,v, m,n
  25.     gcd = b
  26.     return gcd, x, y
  27.  
  28. def modinv(a, m):
  29.     gcd, x, y = egcd(a, m)
  30.     if gcd != 1:
  31.         return None
  32.     else:
  33.         return x % m
  34.  
  35. ''' RSA encryption/decryption class.
  36. '''
  37. class RSA(object):
  38.     _e, _d = 0, 0
  39.     def __init__(self, p, q, e=1):
  40.         self.p, self.q = p, q
  41.         self.n = p * q
  42.         self.m = (p-1) * (q-1)
  43.         self.e = e
  44.     @property
  45.     def e(self):
  46.         return self._e
  47.     @e.setter
  48.     def e(self, val):
  49.         self._e = val
  50.         self._d = modinv(self.e, self.m)
  51.     @property
  52.     def d(self):
  53.         return self._d
  54.     def encrypt(self, M):
  55.         def _encrypt(_m, _e, _n):
  56.             return int(pow(_m, _e) % _n)
  57.         return [_encrypt(m, self.e, self.n) for m in M]
  58.     def decrypt(self, C):
  59.         def _decrypt(_c, _d, _n):
  60.             return int(pow(_c, _d) % _n)
  61.         return [_decrypt(c, self.d, self.n) for c in C]
  62.  
  63. if __name__ == '__main__':
  64.     r = RSA(19, 11, 13)
  65.     plaintext = 'My name is Ryan! What is your name?'
  66.     M = str_to_ascii(plaintext)
  67.     print 'M =', M
  68.     C = r.encrypt(M)
  69.     print 'C =', C
  70.     M1 = r.decrypt(C)
  71.     output = ascii_to_str(M1)
  72.     print plaintext, '==', output, '?=', plaintext == output
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement