-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcaesars-cipher.py
73 lines (67 loc) · 2.36 KB
/
caesars-cipher.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
from typing import List
class CaesarsCipher:
def __init__(self):
self.getOperation()
def getMessageAndKey(self, mode: str) -> List[str]:
message = input("Enter message to be "+ mode + " : ")
flag = True
while flag:
cipherKey = input("Enter the cipher key : ")
if int(cipherKey) >=1 and int(cipherKey) <= 26:
flag = False
return [message, int(cipherKey)]
def encrypt(self):
encryptedText = ''
inputParams = self.getMessageAndKey('encrypted')
message, cipherKey = inputParams[0], inputParams[1]
for char in message:
if char.isalpha():
shift = ord(char)+cipherKey
if char.isupper():
if shift > 90:
shift -= 26
elif shift < 65:
shift += 26
elif char.islower():
if shift > 122:
shift -= 26
elif shift < 97:
shift +=26
encryptedText += chr(shift)
else:
encryptedText += char
print(encryptedText)
def decrypt(self):
decryptedText = ''
inputParams = self.getMessageAndKey('decrypted')
message, cipherKey = inputParams[0], inputParams[1]
for char in message:
if char.isalpha():
shift = ord(char)-cipherKey
if char.isupper():
if shift > 90:
shift -= 26
elif shift < 65:
shift += 26
elif char.islower():
if shift > 122:
shift -= 26
elif shift < 97:
shift +=26
decryptedText += chr(shift)
else:
decryptedText += char
print(decryptedText)
global operationDict
operationDict = {
'encrypt': encrypt,
'decrypt': decrypt
}
def getOperation(self):
flag = True
while flag:
operation = input("Enter \"encrypt\" or \"decrypt\" : ").lower()
if operation == 'encrypt' or operation == 'decrypt':
flag = False
return operationDict[operation](self)
CaesarsCipher()