2014-04-20 19:43:22 +02:00
|
|
|
from string import ascii_lowercase
|
2014-04-08 00:17:34 -03:00
|
|
|
from time import time
|
|
|
|
|
import random
|
|
|
|
|
|
2014-04-20 19:43:22 +02:00
|
|
|
|
2014-04-08 00:17:34 -03:00
|
|
|
class Cipher:
|
2014-04-20 19:43:22 +02:00
|
|
|
|
2015-09-02 16:14:03 +02:00
|
|
|
def __init__(self, key=None):
|
|
|
|
|
if not key:
|
2014-04-08 00:17:34 -03:00
|
|
|
random.seed(time())
|
2015-09-02 16:14:03 +02:00
|
|
|
key = ''.join(random.choice(ascii_lowercase) for i in range(100))
|
|
|
|
|
elif not key.isalpha() or not key.islower():
|
|
|
|
|
raise ValueError('Wrong key parameter!')
|
|
|
|
|
self.key = key
|
2014-04-20 19:43:22 +02:00
|
|
|
|
2015-09-02 16:22:17 +02:00
|
|
|
def encode(self, text):
|
|
|
|
|
text = ''.join(c for c in text if c.isalpha()).lower()
|
|
|
|
|
key = self.key * (len(text) // len(self.key) + 1)
|
|
|
|
|
return ''.join(chr((ord(c) - 194 + ord(k)) % 26 + 97)
|
|
|
|
|
for c, k in zip(text, key))
|
2014-04-20 19:43:22 +02:00
|
|
|
|
2015-09-02 16:22:17 +02:00
|
|
|
def decode(self, text):
|
|
|
|
|
key = self.key * (len(text) // len(self.key) + 1)
|
|
|
|
|
return ''.join(chr((ord(c) - ord(k) + 26) % 26 + 97)
|
|
|
|
|
for c, k in zip(text, key))
|
2014-04-08 00:17:34 -03:00
|
|
|
|
2014-04-20 19:43:22 +02:00
|
|
|
|
2014-04-08 00:17:34 -03:00
|
|
|
class Caesar(Cipher):
|
2014-04-20 19:43:22 +02:00
|
|
|
|
2014-04-08 00:17:34 -03:00
|
|
|
def __init__(self):
|
|
|
|
|
Cipher.__init__(self, 'd')
|