Created
September 2, 2022 23:54
-
-
Save carrickkv2/4475112112c7da6248282b57f2c07163 to your computer and use it in GitHub Desktop.
Encrypts or decrypts a message using the caesar cipher algorithm.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import string | |
list_of_alphabets_and_digits = [ | |
string.ascii_lowercase, | |
string.ascii_uppercase, | |
string.digits, | |
] | |
def shift(alphabets_and_digits_to_shift: str, key_to_shift_by: int) -> str: | |
""" | |
Shift any digits and alphabets that are passed in. | |
""" | |
return ( | |
alphabets_and_digits_to_shift[key_to_shift_by:] | |
+ alphabets_and_digits_to_shift[:key_to_shift_by] | |
) | |
def encrypt_or_decrypt_text( | |
message: str, key: int, alphabets_and_digits: list[str], decrypt_or_encrypt: bool | |
) -> str: | |
""" | |
This function encrypts or decrypts a text that has been passed in | |
and returns the encrypted / decrypted text. | |
""" | |
shifted_alphabets_and_digits = [ | |
shift(value, key) for value in alphabets_and_digits | |
] # Call the shift function with alphabets_and_digits using a list comprehension | |
# turn characters in the list into a string | |
joined_alphabets_and_digits = "".join(alphabets_and_digits) | |
joined_shifted_alphabets_and_digits = "".join(shifted_alphabets_and_digits) | |
if decrypt_or_encrypt is True: | |
mapping_table = str.maketrans( | |
joined_alphabets_and_digits, joined_shifted_alphabets_and_digits | |
) # Create a mapping table | |
else: | |
mapping_table = str.maketrans( | |
joined_shifted_alphabets_and_digits, joined_alphabets_and_digits | |
) | |
return message.translate( | |
mapping_table | |
) # Use the mapping table to replace characters in | |
# the original message with the shifted characters | |
print("Heya. Welcome to the Caesar Cipher Program\n") | |
choose_decryption_or_encryption = input( | |
"Please type yes if you'll like to like encrypt a message or no if you'll like to decrypt a message: \n" | |
).lower() | |
choose_decryption_or_encryption = ( | |
True if choose_decryption_or_encryption == "yes" else False | |
) | |
message = input("\nPlease type the message you'll like to encrypt_or_decrypt\n") | |
key = int( | |
input( | |
"\nPlease type the key you'll like to encrypt_or_decrypt the message with.\n" | |
"This should be a positive integer between the range of 0 to 25. \n" | |
) | |
) | |
if __name__ == "__main__": | |
print(f"\n{encrypt_or_decrypt_text(message, key, list_of_alphabets_and_digits, choose_decryption_or_encryption)}") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment