forked from TheAlgorithms/Python
-
Notifications
You must be signed in to change notification settings - Fork 0
/
simple_substitution_cipher.py
70 lines (55 loc) · 1.71 KB
/
simple_substitution_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
import sys, random
LETTERS = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
def main():
message = input('Enter message: ')
key = 'LFWOAYUISVKMNXPBDCRJTQEGHZ'
resp = input('Encrypt/Decrypt [e/d]: ')
checkValidKey(key)
if resp.lower().startswith('e'):
mode = 'encrypt'
translated = encryptMessage(key, message)
elif resp.lower().startswith('d'):
mode = 'decrypt'
translated = decryptMessage(key, message)
print('\n%sion: \n%s' % (mode.title(), translated))
def checkValidKey(key):
keyList = list(key)
lettersList = list(LETTERS)
keyList.sort()
lettersList.sort()
if keyList != lettersList:
sys.exit('Error in the key or symbol set.')
def encryptMessage(key, message):
"""
>>> encryptMessage('LFWOAYUISVKMNXPBDCRJTQEGHZ', 'Harshil Darji')
'Ilcrism Olcvs'
"""
return translateMessage(key, message, 'encrypt')
def decryptMessage(key, message):
"""
>>> decryptMessage('LFWOAYUISVKMNXPBDCRJTQEGHZ', 'Ilcrism Olcvs')
'Harshil Darji'
"""
return translateMessage(key, message, 'decrypt')
def translateMessage(key, message, mode):
translated = ''
charsA = LETTERS
charsB = key
if mode == 'decrypt':
charsA, charsB = charsB, charsA
for symbol in message:
if symbol.upper() in charsA:
symIndex = charsA.find(symbol.upper())
if symbol.isupper():
translated += charsB[symIndex].upper()
else:
translated += charsB[symIndex].lower()
else:
translated += symbol
return translated
def getRandomKey():
key = list(LETTERS)
random.shuffle(key)
return ''.join(key)
if __name__ == '__main__':
main()