|
| 1 | +import sys # The sys module for system-related operations. |
| 2 | +from colorama import Fore, init # Import the colorama for colored text |
| 3 | + |
| 4 | +init() # Initialize the colorama library for colored text. |
| 5 | + |
| 6 | + |
| 7 | +def implement_caesar_cipher(message, key, decrypt=False): |
| 8 | + # Initialize an empty string to store the result. |
| 9 | + result = "" |
| 10 | + # Iterate through each character in the user's input message. |
| 11 | + for character in message: |
| 12 | + # Check if the character is an alphabet letter. |
| 13 | + if character.isalpha(): |
| 14 | + # Determine the shift amount based. i.e the amount of times to be shifted e.g 2,3,4.... |
| 15 | + shift = key if not decrypt else -key |
| 16 | + # Check if the character is a lowercase letter. |
| 17 | + if character.islower(): |
| 18 | + # Apply Caesar cipher transformation for lowercase letters. |
| 19 | + result += chr(((ord(character) - ord('a') + shift) % 26) + ord('a')) |
| 20 | + else: |
| 21 | + # Apply Caesar cipher transformation for uppercase letters. |
| 22 | + result += chr(((ord(character) - ord('A') + shift) % 26) + ord('A')) |
| 23 | + else: |
| 24 | + # Preserve non-alphabet characters as they are. |
| 25 | + result += character |
| 26 | + return result # Return the encrypted or decrypted result. |
| 27 | + |
| 28 | + |
| 29 | +# Prompt the user to enter the text to be encrypted |
| 30 | +text_to_encrypt = input(f"{Fore.GREEN}[?] Please Enter your text/message: ") |
| 31 | +# Prompt the user to specify the shift length (the key). |
| 32 | +key = int(input(f"{Fore.GREEN}[?] Please specify the shift length: ")) |
| 33 | + |
| 34 | + |
| 35 | +# Check if the specified key is within a valid range (0 to 25). |
| 36 | +if key > 25 or key < 0: |
| 37 | + # Display an error message if the key is out of range. |
| 38 | + print(f"{Fore.RED}[!] Your shift length should be between 0 and 25 ") |
| 39 | + sys.exit() # Exit the program if the key is invalid. |
| 40 | + |
| 41 | +# Encrypt the user's input using the specified key. |
| 42 | +encrypted_text = implement_caesar_cipher(text_to_encrypt, key) |
| 43 | + |
| 44 | +# Display the encrypted text. |
| 45 | +print(f"{Fore.GREEN}[+] {text_to_encrypt} {Fore.MAGENTA}has been encrypted as {Fore.RED}{encrypted_text}") |
| 46 | + |
0 commit comments