0% found this document useful (0 votes)
25 views6 pages

Advance-Level Assignment Problem 1: Symmetric Encryption Service

The document describes solutions to three encryption problems: 1) A symmetric encryption service that allows encrypting and decrypting files using AES with a randomly generated key. 2) A Caesar cipher tool with a user interface to encrypt and decrypt text using shift ciphers. 3) Extending the Caesar cipher to handle uppercase/lowercase and wrapping behavior.

Uploaded by

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

Advance-Level Assignment Problem 1: Symmetric Encryption Service

The document describes solutions to three encryption problems: 1) A symmetric encryption service that allows encrypting and decrypting files using AES with a randomly generated key. 2) A Caesar cipher tool with a user interface to encrypt and decrypt text using shift ciphers. 3) Extending the Caesar cipher to handle uppercase/lowercase and wrapping behavior.

Uploaded by

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

Advance-level Assignment

Problem 1: Symmetric Encryption Service


Objective: Write a program that allows users to encrypt and decrypt files using a
symmetric encryption algorithm (AES). The program should generate a secure key
dynamically and provide options for the user to specify the encryption mode.
Key Concepts: AES, key management, encryption modes

Solution.:
from Crypto.Cipher import AES
from Crypto.Random import get_random_bytes
from Crypto.Util.Padding import pad, unpad
def generate_key(key_size):
"""
Generates a secure random key for AES encryption.
Args:
key_size: Key size in bits (128, 192, or 256).
Returns:
A byte string of the random key.
"""
if key_size not in [128, 192, 256]:
raise ValueError("Invalid key size. Choose 128, 192, or 256 bits.")
return get_random_bytes(key_size // 8)

def encrypt_file(input_file, output_file, key, mode, iv=None):


"""
Encrypts a file using AES in the specified mode.
Args
input_file: Path to the file to encrypt.
output_file: Path to write the encrypted file.
key: The secret key for encryption (byte string).
mode: The encryption mode (e.g., 'CBC', 'EAX').
iv: Initialization Vector (optional, required for some modes).
"""
cipher = AES.new(key, mode, iv)
with open(input_file, 'rb') as infile, open(output_file, 'wb') as outfile:
data = infile.read()
padded_data = pad(data, AES.block_size)
ciphertext = cipher.encrypt(padded_data)
if iv:
outfile.write(iv) # Write IV for decryption
outfile.write(ciphertext)

def decrypt_file(input_file, output_file, key, mode, iv=None):


"""
Decrypts a file using AES in the specified mode.
Args:
input_file: Path to the encrypted file.
output_file: Path to write the decrypted file.
key: The secret key for decryption (byte string).
mode: The encryption mode used (e.g., 'CBC', 'EAX').
iv: Initialization Vector (optional, required for some modes).
"""
if iv:
iv = iv[:AES.block_size] # Ensure IV is correct size
cipher = AES.new(key, mode, iv)
with open(input_file, 'rb') as infile, open(output_file, 'wb') as outfile:
if iv:
iv = infile.read(AES.block_size) # Read IV from encrypted file
ciphertext = infile.read()
decrypted_data = cipher.decrypt(ciphertext)
data = unpad(decrypted_data, AES.block_size)
outfile.write(data)

def main():
"""
Prompts user for encryption/decryption, file paths, key size, and mode.
"""
operation = input("Enter 'e' to encrypt or 'd' to decrypt: ")
if operation not in ['e', 'd']:
print("Invalid operation. Exiting...")
return

input_file = input("Enter the path to the file: ")


output_file = input("Enter the output file path: ")
key_size = int(input("Choose key size (128, 192, or 256 bits): "))
key = generate_key(key_size)
# Get mode selection from user (replace with your preferred method)
print("Available modes: CBC, EAX (choose one)")
mode = input("Enter the encryption mode: ").upper()
# Handle Initialization Vector (IV) based on mode (if needed)
iv = None
if mode in ['CBC', 'GCM']:
iv = get_random_bytes(AES.block_size)
if operation == 'e':
encrypt_file(input_file, output_file, key, mode, iv)
print("File encrypted successfully!")
else:
decrypt_file(input_file, output_file, key, mode, iv)
print("File decrypted successfully!")
if __name__ == "__main__":
main()

Problem 3: Caesar Cipher Tool


Objective: Implement a Caesar cipher tool with a user-friendly interface that
allows users to encrypt and decrypt text. Include options for shifting and wrap-
around handling.
Solution.:

def encrypt_caesar(text, shift, wrap_around):


"""
Encrypts text using Caesar cipher with user-defined shift and wrap-around option.
Args:
text: The text to encrypt (string).
shift: The amount to shift letters (integer).
wrap_around: Boolean flag indicating wrap-around behavior.

Returns:
The encrypted text (string).
"""
result = ""
for char in text:
if char.isalpha():
# Get uppercase/lowercase status
is_uppercase = char.isupper()
# Convert char to numerical value (A=0, Z=25)
char_num = ord(char) - (65 if is_uppercase else 97)
# Apply shift
new_num = (char_num + shift) % 26
# Convert back to character with wrap-around handling
new_char = chr(new_num + (65 if is_uppercase else 97))
if wrap_around and not is_uppercase and new_char < 'a':
new_char = chr(ord('z') - (new_num - 1))
elif wrap_around and is_uppercase and new_char > 'Z':
new_char = chr(ord('A') + (new_num - 1))
result += new_char
else:
result += char
return result

def decrypt_caesar(text, shift, wrap_around):


"""
Decrypts text using Caesar cipher with user-defined shift and wrap-around option.

Args:
text: The text to decrypt (string).
shift: The amount to shift letters (integer).
wrap_around: Boolean flag indicating wrap-around behavior.

Returns:
The decrypted text (string).
"""
return encrypt_caesar(text, -shift, wrap_around) # Decrypt by negating shift

def main():
"""
Provides user interface for Caesar cipher encryption and decryption.
"""
while True:
print("\nCaesar Cipher Tool")
print("1. Encrypt")
print("2. Decrypt")
print("3. Exit")
choice = input("Enter your choice (1-3): ")

if choice == '1':
text = input("Enter text to encrypt: ")
shift = int(input("Enter shift amount (positive integer): "))
wrap_around = input("Enable wrap-around? (y/n): ").lower() == 'y'
encrypted_text = encrypt_caesar(text, shift, wrap_around)
print("Encrypted text:", encrypted_text)
elif choice == '2':
text = input("Enter text to decrypt: ")
shift = int(input("Enter shift amount (positive integer): "))
wrap_around = input("Enable wrap-around? (y/n): ").lower() == 'y'
decrypted_text = decrypt_caesar(text, shift, wrap_around)
print("Decrypted text:", decrypted_text)
elif choice == '3':
print("Exiting...")
break
else:
print("Invalid choice. Please try again.")

if __name__ == "__main__":
main()

You might also like