-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsubstitutionCipher.py
More file actions
51 lines (43 loc) · 1.47 KB
/
substitutionCipher.py
File metadata and controls
51 lines (43 loc) · 1.47 KB
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
# ===================
# Substitution Cipher
# ===================
from affineCipher import encrypt
import random
SYMBOLS = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
def encrypt(key, plaintext):
return translatedMessage(key, plaintext, 'encrypt')
def decrypt(key, ciphertext):
return translatedMessage(key, ciphertext, 'decrypt')
# return trnaslated message
def translatedMessage(key, message, mode):
translated = ''
charsA = SYMBOLS
charsB = key
if mode == 'decrypt': # decryption happens with swapped symbol indexes
charsA, charsB = charsB, charsA
# translate each symbol in message, adding it to translated string
for symbol in message:
if symbol.upper() in charsA:
symbolIndex = charsA.find(symbol.upper())
if symbol.isupper():
translated += charsB[symbolIndex].upper()
else:
translated += charsB[symbolIndex].lower()
else:
translated += symbol
return translated
def main():
message = 'Times are harder than we thought, and that is what makes soft men hard'
letters = list(SYMBOLS) # generate random key
random.shuffle(letters)
key = ''.join(letters)
mode = 'encrypt'
if mode == 'encrypt':
translated = encrypt(key, message)
elif mode == 'decrypt':
translated = decrypt(key, message)
print('Using key: %s' % (key))
print('The %sed message is:' % (mode))
print(translated)
if __name__ == '__main__':
main()