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