Basics of Symmetric Encryption Algorithms
Laboratory Work: Basics of Symmetric Encryption Algorithms
Objective
To study the basics of symmetric encryption algorithms using simple algorithms such as Caesar, Vigenère, and XOR ciphers. To acquire skills in implementing these algorithms in a programming language and learn how to use them to exchange encrypted messages.
Equipment and Software
- A computer with an installed development environment (e.g., Python).
- Basic knowledge of a programming language (e.g., Python).
Theoretical Part
Caesar Cipher
The Caesar cipher is a simple encryption method where each letter in the plaintext is replaced by a letter a fixed number of positions down the alphabet. For example, with a shift of 3, A becomes D, B becomes E, and so on.
Vigenère Cipher
The Vigenère cipher uses a keyword to encrypt a message. Each letter in the message is shifted by a number of positions determined by the corresponding letter in the keyword. If the keyword is shorter than the message, it is repeated.
XOR Cipher
The XOR cipher is a simple symmetric encryption algorithm that operates by performing the XOR (exclusive OR) operation on the binary representation of the data using a key. If the key is shorter than the data, it is repeated.
Task 1: Implementing the Caesar Cipher
- Implement a function to encrypt a message using the Caesar cipher.
- Implement a function to decrypt a message using the Caesar cipher.
- Write a program that asks the user for a message and a shift key, encrypts the message, and outputs the result.
- Add a function for interaction with other students: the program should be able to receive encrypted messages, decrypt them, and display the original text.
Example Code (Python):
def caesar_encrypt(text, shift):
encrypted_text = ""
for char in text:
if char.isalpha():
shift_base = 65 if char.isupper() else 97
encrypted_text += chr((ord(char) - shift_base + shift) % 26 + shift_base)
else:
encrypted_text += char
return encrypted_text
def caesar_decrypt(text, shift):
return caesar_encrypt(text, -shift)
# Example usage
message = input("Enter the message to encrypt: ")
while True:
try:
shift = int(input("Enter the shift key (0-25): "))
if 0 <= shift <= 25:
break
else:
print("Please enter a valid shift key between 0 and 25.")
except ValueError:
print("Invalid input. Please enter an integer.")
encrypted_message = caesar_encrypt(message, shift)
print("Encrypted message:", encrypted_message)
# For decryption
received_message = input("Enter the received encrypted message: ")
decrypted_message = caesar_decrypt(received_message, shift)
print("Decrypted message:", decrypted_message)
Task 2: Implementing the Vigenère Cipher
- Implement a function to encrypt a message using the Vigenère cipher.
- Implement a function to decrypt a message using the Vigenère cipher.
- Write a program that asks the user for a message and a keyword, encrypts the message, and outputs the result.
- Add a function for interaction with other students: the program should be able to receive encrypted messages, decrypt them, and display the original text.
Example Code (Python):
def vigenere_encrypt(text, keyword):
keyword_repeated = ''.join([keyword[i % len(keyword)] for i in range(len(text)) if text[i].isalpha()])
encrypted_text = ""
keyword_index = 0
for i in range(len(text)):
if text[i].isalpha():
shift_base = 65 if text[i].isupper() else 97
shift = ord(keyword_repeated[keyword_index].lower()) - 97
encrypted_text += chr((ord(text[i]) - shift_base + shift) % 26 + shift_base)
keyword_index += 1
else:
encrypted_text += text[i]
return encrypted_text
def vigenere_decrypt(text, keyword):
keyword_repeated = ''.join([keyword[i % len(keyword)] for i in range(len(text)) if text[i].isalpha()])
decrypted_text = ""
keyword_index = 0
for i in range(len(text)):
if text[i].isalpha():
shift_base = 65 if text[i].isupper() else 97
shift = ord(keyword_repeated[keyword_index].lower()) - 97
decrypted_text += chr((ord(text[i]) - shift_base - shift + 26) % 26 + shift_base)
keyword_index += 1
else:
decrypted_text += text[i]
return decrypted_text
# Example usage
message = input("Enter the message to encrypt: ")
keyword = input("Enter the keyword: ")
encrypted_message = vigenere_encrypt(message, keyword)
print("Encrypted message:", encrypted_message)
# For decryption
received_message = input("Enter the received encrypted message: ")
decrypted_message = vigenere_decrypt(received_message, keyword)
print("Decrypted message:", decrypted_message)
Task 3: Implementing the XOR Cipher
- Implement a function to encrypt a message using the XOR cipher.
- Implement a function to decrypt a message using the XOR cipher.
- Write a program that asks the user for a message and a key, encrypts the message, and outputs the result.
- Add a function for interaction with other students: the program should be able to receive encrypted messages, decrypt them, and display the original text.
Example Code (Python):
def xor_encrypt(text, key):
# Convert text and key to bytes
text_bytes = text.encode('utf-8')
key_bytes = key.encode('utf-8')
key_length = len(key_bytes)
encrypted_bytes = bytearray()
for i in range(len(text_bytes)):
encrypted_byte = text_bytes[i] ^ key_bytes[i % key_length]
encrypted_bytes.append(encrypted_byte)
return encrypted_bytes
def to_hex_string(byte_array):
return ''.join(f'{byte:02x}' for byte in byte_array)
def from_hex_string(hex_string):
return bytearray(int(hex_string[i:i+2], 16) for i in range(0, len(hex_string), 2))
def xor_decrypt(encrypted_bytes, key):
key_bytes = key.encode('utf-8')
key_length = len(key_bytes)
decrypted_bytes = bytearray()
for i in range(len(encrypted_bytes)):
decrypted_byte = encrypted_bytes[i] ^ key_bytes[i % key_length]
decrypted_bytes.append(decrypted_byte)
# Decode the byte array back to a string
return decrypted_bytes.decode('utf-8')
# Example usage
message = input("Enter the message to encrypt: ")
key = input("Enter the key: ")
encrypted_message = xor_encrypt(message, key)
hex_encrypted_message = to_hex_string(encrypted_message)
print("Encrypted message (in hex):", hex_encrypted_message)
# For decryption
received_hex_message = input("Enter the received encrypted message (in hex): ")
encrypted_bytes = from_hex_string(received_hex_message)
decrypted_message = xor_decrypt(encrypted_bytes, key)
print("Decrypted message:", decrypted_message)
Task 4: Exchanging Encrypted Messages
- Organize an exchange of encrypted messages with other students.
- Use the implemented algorithms (Caesar, Vigenère, XOR) for encrypting and decrypting messages.
- Each student should encrypt a message using one of the algorithms and send it to another student for decryption.
Example Sequence of Actions:
- Student A creates an encrypted message using the Caesar, Vigenère, or XOR cipher.
- Student A sends the encrypted message to Student B.
- Student B receives the message and decrypts it using the corresponding algorithm.
- Student B sends their encrypted response to Student A.
- The process repeats.
Lab Report
- Description of the implementation of the Caesar, Vigenère, and XOR ciphers.
- Examples of encrypted and decrypted messages.
- Log of interactions with other students (what messages were sent and received).
- Conclusions from the work.
Saving and Loading Information in Files
Saving Information to a File
Writing to a Text File
Appending Data to a File
Writing Data to a File as a List of Strings
Loading Information from a File
Reading from a Text File
Reading a File Line by Line
Reading a File One Line at a Time
Example: Saving and Loading Encrypted Messages
Saving an Encrypted Message to a File
Loading an Encrypted Message from a File
Tips and Recommendations
- Always use the
with open
construct to ensure the file is closed after operations are complete. - Be aware of the file opening modes:
'r'
— reading (the file must exist)'w'
— writing (an existing file will be overwritten)'a'
— appending (data will be added to the end of the file)'b'
— binary mode (e.g.,'rb'
or'wb'
for reading or writing binary data)