Python/ciphers/simple_substitution_cipher.py

79 lines
1.8 KiB
Python
Raw Normal View History

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