Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #!/usr/bin/env python
- ''' Convert to and from ASCII text.
- '''
- def str_to_ascii(s):
- return [ord(c) for c in s]
- def ascii_to_str(l):
- return ''.join(chr(x) for x in l)
- ''' Define math operations.
- '''
- def pow(x, n):
- r = x
- for i in range(n-1):
- r = r * x
- return r
- def egcd(a, b):
- x,y, u,v = 0,1, 1,0
- while a != 0:
- q, r = b//a, b%a
- m, n = x-u*q, y-v*q
- b,a, x,y, u,v = a,r, u,v, m,n
- gcd = b
- return gcd, x, y
- def modinv(a, m):
- gcd, x, y = egcd(a, m)
- if gcd != 1:
- return None
- else:
- return x % m
- ''' RSA encryption/decryption class.
- '''
- class RSA(object):
- _e, _d = 0, 0
- def __init__(self, p, q, e=1):
- self.p, self.q = p, q
- self.n = p * q
- self.m = (p-1) * (q-1)
- self.e = e
- @property
- def e(self):
- return self._e
- @e.setter
- def e(self, val):
- self._e = val
- self._d = modinv(self.e, self.m)
- @property
- def d(self):
- return self._d
- def encrypt(self, M):
- def _encrypt(_m, _e, _n):
- return int(pow(_m, _e) % _n)
- return [_encrypt(m, self.e, self.n) for m in M]
- def decrypt(self, C):
- def _decrypt(_c, _d, _n):
- return int(pow(_c, _d) % _n)
- return [_decrypt(c, self.d, self.n) for c in C]
- if __name__ == '__main__':
- r = RSA(19, 11, 13)
- plaintext = 'My name is Ryan! What is your name?'
- M = str_to_ascii(plaintext)
- print 'M =', M
- C = r.encrypt(M)
- print 'C =', C
- M1 = r.decrypt(C)
- output = ascii_to_str(M1)
- print plaintext, '==', output, '?=', plaintext == output
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement