TheAlgorithms-Python/ciphers/simple_substitution_cipher.py

78 lines
1.7 KiB
Python
Raw Normal View History

2016-08-01 12:56:52 +05:30
import sys, random
2019-10-05 01:14:13 -04:00
LETTERS = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
2016-08-01 12:56:52 +05:30
def main():
2019-10-05 01:14:13 -04:00
message = input("Enter message: ")
key = "LFWOAYUISVKMNXPBDCRJTQEGHZ"
resp = input("Encrypt/Decrypt [e/d]: ")
2016-08-01 12:56:52 +05:30
checkValidKey(key)
2019-10-05 01:14:13 -04:00
if resp.lower().startswith("e"):
mode = "encrypt"
2016-08-01 12:56:52 +05:30
translated = encryptMessage(key, message)
2019-10-05 01:14:13 -04:00
elif resp.lower().startswith("d"):
mode = "decrypt"
2016-08-01 12:56:52 +05:30
translated = decryptMessage(key, message)
print("\n{}ion: \n{}".format(mode.title(), translated))
2019-10-05 01:14:13 -04:00
2016-08-01 12:56:52 +05:30
def checkValidKey(key):
keyList = list(key)
lettersList = list(LETTERS)
keyList.sort()
lettersList.sort()
if keyList != lettersList:
2019-10-05 01:14:13 -04:00
sys.exit("Error in the key or symbol set.")
2016-08-01 12:56:52 +05:30
def encryptMessage(key, message):
2016-08-02 23:16:55 +05:30
"""
>>> encryptMessage('LFWOAYUISVKMNXPBDCRJTQEGHZ', 'Harshil Darji')
'Ilcrism Olcvs'
"""
2019-10-05 01:14:13 -04:00
return translateMessage(key, message, "encrypt")
2016-08-01 12:56:52 +05:30
def decryptMessage(key, message):
2016-08-02 23:16:55 +05:30
"""
>>> decryptMessage('LFWOAYUISVKMNXPBDCRJTQEGHZ', 'Ilcrism Olcvs')
'Harshil Darji'
"""
2019-10-05 01:14:13 -04:00
return translateMessage(key, message, "decrypt")
2016-08-01 12:56:52 +05:30
def translateMessage(key, message, mode):
2019-10-05 01:14:13 -04:00
translated = ""
2016-08-01 12:56:52 +05:30
charsA = LETTERS
charsB = key
2019-10-05 01:14:13 -04:00
if mode == "decrypt":
2016-08-01 12:56:52 +05:30
charsA, charsB = charsB, charsA
2016-08-01 12:56:52 +05:30
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
2019-10-05 01:14:13 -04:00
2016-08-01 12:56:52 +05:30
def getRandomKey():
key = list(LETTERS)
random.shuffle(key)
2019-10-05 01:14:13 -04:00
return "".join(key)
2016-08-01 12:56:52 +05:30
2019-10-05 01:14:13 -04:00
if __name__ == "__main__":
2016-08-01 12:56:52 +05:30
main()