-
Notifications
You must be signed in to change notification settings - Fork 0
/
caesarcipher.py
52 lines (44 loc) · 1.47 KB
/
caesarcipher.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
# Caesar Cipher
SYMBOLS = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'
MAX_KEY_SIZE = len(SYMBOLS)
def getMode():
while True:
print('Do you wish to encrypt or decrypt a message?')
mode = input().lower()
if mode in ['encrypt', 'e', 'decrypt', 'd']:
return mode
else:
print('Enter either "encrypt" or "e" or "decrypt" or "d".')
def getMessage():
print('Enter your message:')
return input()
def getKey():
key = 0
while True:
print('Enter the key number (1-%s)' % (MAX_KEY_SIZE))
key = int(input())
if (key >= 1 and key <= MAX_KEY_SIZE):
return key
def getTranslatedMessage(mode, message, key):
if mode[0] == 'd':
key = -key
translated = ''
for symbol in message:
symbolIndex = SYMBOLS.find(symbol)
if symbolIndex == -1: # Symbol not found in SYMBOLS.
# Just add this symbol without any change.
translated += symbol
else:
# Encrypt or decrypt
symbolIndex += key
if symbolIndex >= len(SYMBOLS):
symbolIndex -= len(SYMBOLS)
elif symbolIndex < 0:
symbolIndex += len(SYMBOLS)
translated += SYMBOLS[symbolIndex]
return translated
mode = getMode()
message = getMessage()
key = getKey()
print('Your translated text is:')
print(getTranslatedMessage(mode, message, key))