Professional Documents
Culture Documents
Advance-Level Assignment Problem 1: Symmetric Encryption Service
Advance-Level Assignment Problem 1: Symmetric Encryption Service
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 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
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
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()