Thanks to visit codestin.com
Credit goes to www.scribd.com

0% found this document useful (0 votes)
45 views4 pages

Caesar Cipher Encryption Tool

This document defines functions for a Caesar cipher encryption/decryption program. It contains functions to encrypt and decrypt text using a shift value, get a valid shift value from the user, and a main function to run the program. The main function handles user input, encrypts/decrypts text, saves results to files, and allows changing the shift value or exiting the program.

Uploaded by

mateiromica89
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
45 views4 pages

Caesar Cipher Encryption Tool

This document defines functions for a Caesar cipher encryption/decryption program. It contains functions to encrypt and decrypt text using a shift value, get a valid shift value from the user, and a main function to run the program. The main function handles user input, encrypts/decrypts text, saves results to files, and allows changing the shift value or exiting the program.

Uploaded by

mateiromica89
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
You are on page 1/ 4

# Print the name of the program

print(" ""-----"" VLAD'S CYPHER ENCRYPTION/DECRYPTION PROGRAM


""-----")

# Make a pause between the name of the program and the rest of the code
print("")

# Define the function to encrypt text using Caesar Cipher


def encrypt(text, shift):
# Define the alphabet for reference
alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"
# Initialize an empty string to store the encrypted text
encrypted_text = ""

# Iterate through each character in the input text


for char in text:
# Check if the character is alphabetic
if char.isalpha():
# Determine if the original character is uppercase
is_upper = char.isupper()
# Find the position of the character in the alphabet
position = alphabet.find(char.upper())
# Calculate the new position after shifting
new_position = (position + shift) % 26
# Append the encrypted character to the result
encrypted_text += alphabet[new_position].upper() if is_upper else
alphabet[new_position].lower()
else:
# If the character is not alphabetic, keep it unchanged
encrypted_text += char

# Return the encrypted text


return encrypted_text

# Define the function to decrypt text using Caesar Cipher


def decrypt(text, shift):
# Define the alphabet for reference
alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"
# Initialize an empty string to store the decrypted text
decrypted_text = ""

# Iterate through each character in the input text


for char in text:
# Check if the character is alphabetic
if char.isalpha():
# Determine if the original character is uppercase
is_upper = char.isupper()
# Find the position of the character in the alphabet
position = alphabet.find(char.upper())
# Calculate the new position after shifting in reverse
new_position = (position - shift) % 26
# Append the decrypted character to the result
decrypted_text += alphabet[new_position].upper() if is_upper else
alphabet[new_position].lower()
else:
# If the character is not alphabetic, keep it unchanged
decrypted_text += char

# Return the decrypted text


return decrypted_text

# Define the function to get a valid shift value from the user
def get_valid_shift():
# Loop until a valid input is provided
while True:
try:
# Try to get a valid integer input from the user
shift = int(input("Please enter a whole number from 1-25 to be your
key: "))
# Check if the entered shift is within the valid range
if 1 <= shift <= 25:
print(f"Shift value {shift} is valid.")
return shift
else:
print("Shift value must be between 1 and 25.")
except ValueError:
# Handle the case where the user enters a non-integer
print("Invalid input. Please enter a valid whole number.")

# Define the main program


def main():
# Define file paths for input and output
input_file_path = "C:\\Users\\30174846\\OneDrive - New College Lanarkshire\\
LVL6 IT&CYBER SECURITY\\SEMESTER 2\\Computer Programming NQ Level 6\\Assessment 2 —
Practical assignment\\ciphers\\CipherInput.txt"
encrypted_output_path = "C:\\Users\\30174846\\OneDrive - New College
Lanarkshire\\LVL6 IT&CYBER SECURITY\\SEMESTER 2\\Computer Programming NQ Level 6\\
Assessment 2 — Practical assignment\\ciphers\\CipherEncrypt.txt"
decrypted_output_path = "C:\\Users\\30174846\\OneDrive - New College
Lanarkshire\\LVL6 IT&CYBER SECURITY\\SEMESTER 2\\Computer Programming NQ Level 6\\
Assessment 2 — Practical assignment\\ciphers\\CipherDecrypt.txt"

try:
# Try to open and read the input file
with open(input_file_path, 'r') as file:
# Read the content of the file
original_text = file.read()
except FileNotFoundError:
# Handle the case where the input file is not found
print(f"Error: Input file not found at CipherInput.txt")
return

# Get a valid shift value from the user


shift_amount = get_valid_shift()

# Main loop for user interaction


while True:
# Print the available options
print("\nOptions:")
print("1. Encrypt and save to file")
print("2. Decrypt and save to file")
print("3. Change shift value")
print("4. Exit")

# Get user choice


option = input("Enter your choice (1, 2, 3, or 4): ")

if option == '1':
# Encrypt and save to file
encrypted_result = encrypt(original_text, shift_amount)
try:
with open(encrypted_output_path, 'w') as encrypted_file:
# Write original and encrypted text to the file
encrypted_file.write(f"Original Text:\n{original_text}\n\n")
encrypted_file.write(f"Encrypted Text (Shift={shift_amount}):\
n{encrypted_result}")
print(f"Encrypted result saved to CipherEncrypt.txt")

# Prompt for decryption or exit


decrypt_option = input("Options:\n1. Decrypt\n2. Change shift
value\n3. Exit\nEnter your choice (1,2, or 3): ")
if decrypt_option == '1':
# Decrypt the encrypted result
decrypted_result = decrypt(encrypted_result, shift_amount)
try:
with open(decrypted_output_path, 'w') as decrypted_file:
# Write decrypted text to the file
decrypted_file.write(f"Decrypted Text
(Shift={shift_amount}):\n{decrypted_result}")
print(f"Decrypted result saved to CipherDecrypt.txt")
# Exit the program
break
except IOError:
print(f"Error: Unable to write to decrypted output file at
CipherDecrypt.txt")
break
elif decrypt_option == '2':
# Change shift value
shift_amount = get_valid_shift()
elif decrypt_option == '3':
# Exit the program
break
else:
print("Invalid choice. Exiting program.")
# Exit the program
break

except IOError:
print(f"Error: Unable to write to encrypted output file at
CipherEncrypt.txt")

elif option == '2':


# Encrypt, then decrypt and save to file
encrypted_result = encrypt(original_text, shift_amount)
try:
with open(encrypted_output_path, 'w') as encrypted_file:
# Write original and encrypted text to the file
encrypted_file.write(f"Original Text:\n{original_text}\n\n")
encrypted_file.write(f"Encrypted Text (Shift={shift_amount}):\
n{encrypted_result}")
print(f"Encrypted result saved to CipherEncrypt.txt")

# Decrypt the encrypted result


decrypted_result = decrypt(encrypted_result, shift_amount)
try:
with open(decrypted_output_path, 'w') as decrypted_file:
# Write decrypted text to the file
decrypted_file.write(f"Decrypted Text
(Shift={shift_amount}):\n{decrypted_result}")
print(f"Decrypted result saved to CipherDecrypt.txt")
except IOError:
print(f"Error: Unable to write to decrypted output file at
CipherDecrypt.txt")

except IOError:
print(f"Error: Unable to write to encrypted output file at
CipherEncrypt.txt")

# Prompt for change shift value or exit


break

elif option == '3':


# Change shift value
shift_amount = get_valid_shift()
elif option == '4':
# Exit the program
break
else:
print("Invalid choice. Please enter a valid option (1, 2, 3, or 4).")

# Check if the script is run as the main program


if __name__ == "__main__":
# Call the main function
main()

You might also like