TheAlgorithms-Python/ciphers/simple_substitution_cipher.py

71 lines
1.7 KiB
Python
Raw Normal View History

2016-08-01 15:26:52 +08:00
import sys, random
LETTERS = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
def main():
2018-10-21 03:45:08 +08:00
message = input('Enter message: ')
2016-08-01 15:26:52 +08:00
key = 'LFWOAYUISVKMNXPBDCRJTQEGHZ'
2018-10-21 03:45:08 +08:00
resp = input('Encrypt/Decrypt [e/d]: ')
2016-08-01 15:26:52 +08:00
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))
2016-08-01 15:26:52 +08:00
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):
2016-08-03 01:46:55 +08:00
"""
>>> encryptMessage('LFWOAYUISVKMNXPBDCRJTQEGHZ', 'Harshil Darji')
'Ilcrism Olcvs'
"""
2016-08-01 15:26:52 +08:00
return translateMessage(key, message, 'encrypt')
def decryptMessage(key, message):
2016-08-03 01:46:55 +08:00
"""
>>> decryptMessage('LFWOAYUISVKMNXPBDCRJTQEGHZ', 'Ilcrism Olcvs')
'Harshil Darji'
"""
2016-08-01 15:26:52 +08:00
return translateMessage(key, message, 'decrypt')
def translateMessage(key, message, mode):
translated = ''
charsA = LETTERS
charsB = key
if mode == 'decrypt':
charsA, charsB = charsB, charsA
2016-08-01 15:26:52 +08:00
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()