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() -> None:
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
check_valid_key(key)
2016-08-01 07:26:52 +00:00
2019-10-05 05:14:13 +00:00
if resp.lower().startswith("e"):
mode = "encrypt"
translated = encrypt_message(key, message)
2019-10-05 05:14:13 +00:00
elif resp.lower().startswith("d"):
mode = "decrypt"
translated = decrypt_message(key, message)
2016-08-01 07:26:52 +00:00
print(f"\n{mode.title()}ion: \n{translated}")
2019-10-05 05:14:13 +00:00
def check_valid_key(key: str) -> None:
key_list = list(key)
letters_list = list(LETTERS)
key_list.sort()
letters_list.sort()
2016-08-01 07:26:52 +00:00
if key_list != letters_list:
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 encrypt_message(key: str, message: str) -> str:
2016-08-02 17:46:55 +00:00
"""
>>> encrypt_message('LFWOAYUISVKMNXPBDCRJTQEGHZ', 'Harshil Darji')
2016-08-02 17:46:55 +00:00
'Ilcrism Olcvs'
"""
return translate_message(key, message, "encrypt")
2019-10-05 05:14:13 +00:00
2016-08-01 07:26:52 +00:00
def decrypt_message(key: str, message: str) -> str:
2016-08-02 17:46:55 +00:00
"""
>>> decrypt_message('LFWOAYUISVKMNXPBDCRJTQEGHZ', 'Ilcrism Olcvs')
2016-08-02 17:46:55 +00:00
'Harshil Darji'
"""
return translate_message(key, message, "decrypt")
2019-10-05 05:14:13 +00:00
2016-08-01 07:26:52 +00:00
def translate_message(key: str, message: str, mode: str) -> str:
2019-10-05 05:14:13 +00:00
translated = ""
chars_a = LETTERS
chars_b = key
2016-08-01 07:26:52 +00:00
2019-10-05 05:14:13 +00:00
if mode == "decrypt":
chars_a, chars_b = chars_b, chars_a
2016-08-01 07:26:52 +00:00
for symbol in message:
if symbol.upper() in chars_a:
sym_index = chars_a.find(symbol.upper())
2016-08-01 07:26:52 +00:00
if symbol.isupper():
translated += chars_b[sym_index].upper()
2016-08-01 07:26:52 +00:00
else:
translated += chars_b[sym_index].lower()
2016-08-01 07:26:52 +00:00
else:
translated += symbol
return translated
2019-10-05 05:14:13 +00:00
def get_random_key() -> str:
2016-08-01 07:26:52 +00:00
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()