TheAlgorithms-Python/ciphers/simple_substitution_cipher.py

79 lines
1.8 KiB
Python
Raw Normal View History

import random
import sys
2016-08-01 12:56:52 +05:30
2019-10-05 01:14:13 -04:00
LETTERS = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
2016-08-01 12:56:52 +05:30
def main() -> None:
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(f"\n{mode.title()}ion: \n{translated}")
2019-10-05 01:14:13 -04:00
def checkValidKey(key: str) -> None:
2016-08-01 12:56:52 +05:30
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: str, message: str) -> str:
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: str, message: str) -> str:
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: str, message: str, mode: str) -> str:
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
def getRandomKey() -> str:
2016-08-01 12:56:52 +05:30
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()