Кафедра ИСиТ УО ВГТУ
  • Специальности
    • Экономика электронного бизнеса
    • Информационные системы
    • Information Control Systems
  • Каталог
  • Сайт кафедры
  • Сервисы
    • GitLab
    • ownCloud
    • JupyterHub
    • JupyterHub 2
    • VNC
    • Soft
  1. ICS
  2. ITCS
  3. Practice
  4. Basics of Symmetric Encryption Algorithms
  • ICS
    • ITCS
      • Theory
        • Computer security issues
        • Computer Security Mechanisms
        • Common Principles of Cryptography
        • Asymmetric encryption
        • Data integrity
        • Steganographic methods for information protection
      • Practice
        • Basics of Symmetric Encryption Algorithms
        • Asymmetric crypto algorithms
        • Data Integrity
    • TSTPI
      • Theory
        • Fundamentals of Data Transmission Networks
        • Fundamentals of digital data transmission
        • Network interconnection using network layer protocols
        • Trends in the development of telecommunication technologies and computer networks
        • Search Engines
        • Information security. Confidential information
      • Practice
        • Basic Network Utilities
        • Installing of Network OS
        • Linux network utilities
        • SSH Protocol
        • User Accounts Management
        • Protocol Analysis Using a Network Traffic Analyzer

Contents

  • Laboratory Work: Basics of Symmetric Encryption Algorithms
    • Objective
    • Equipment and Software
    • Theoretical Part
      • Caesar Cipher
      • Vigenère Cipher
      • XOR Cipher
    • Task 1: Implementing the Caesar Cipher
      • Example Code (Python):
    • Task 2: Implementing the Vigenère Cipher
      • Example Code (Python):
    • Task 3: Implementing the XOR Cipher
      • Example Code (Python):
    • Task 4: Exchanging Encrypted Messages
      • Example Sequence of Actions:
    • Lab Report
    • Saving and Loading Information in Files
      • Saving Information to a File
      • Loading Information from a File
      • Example: Saving and Loading Encrypted Messages
      • Tips and Recommendations
  1. ICS
  2. ITCS
  3. Practice
  4. Basics of Symmetric Encryption Algorithms

Basics of Symmetric Encryption Algorithms

Innovative Technologies for Computer Security
Practice
Author

Andrei Biziuk

Published

November 13, 2024

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

  1. Implement a function to encrypt a message using the Caesar cipher.
  2. Implement a function to decrypt a message using the Caesar cipher.
  3. Write a program that asks the user for a message and a shift key, encrypts the message, and outputs the result.
  4. 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

  1. Implement a function to encrypt a message using the Vigenère cipher.
  2. Implement a function to decrypt a message using the Vigenère cipher.
  3. Write a program that asks the user for a message and a keyword, encrypts the message, and outputs the result.
  4. 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

  1. Implement a function to encrypt a message using the XOR cipher.
  2. Implement a function to decrypt a message using the XOR cipher.
  3. Write a program that asks the user for a message and a key, encrypts the message, and outputs the result.
  4. 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

  1. Organize an exchange of encrypted messages with other students.
  2. Use the implemented algorithms (Caesar, Vigenère, XOR) for encrypting and decrypting messages.
  3. Each student should encrypt a message using one of the algorithms and send it to another student for decryption.

Example Sequence of Actions:

  1. Student A creates an encrypted message using the Caesar, Vigenère, or XOR cipher.
  2. Student A sends the encrypted message to Student B.
  3. Student B receives the message and decrypts it using the corresponding algorithm.
  4. Student B sends their encrypted response to Student A.
  5. The process repeats.

Lab Report

  1. Description of the implementation of the Caesar, Vigenère, and XOR ciphers.
  2. Examples of encrypted and decrypted messages.
  3. Log of interactions with other students (what messages were sent and received).
  4. Conclusions from the work.

Saving and Loading Information in Files

Saving Information to a File

Writing to a Text File

# Open a file for writing (mode 'w' means writing)
with open('filename.txt', 'w') as file:
    file.write("Hello, world!\n")
    file.write("This is a second line.\n")

Appending Data to a File

# Open a file for appending data
with open('filename.txt', 'a') as file:
    file.write("Adding another line.\n")

Writing Data to a File as a List of Strings

lines = ["First line\n", "Second line\n", "Third line\n"]
with open('filename.txt', 'w') as file:
    file.writelines(lines)

Loading Information from a File

Reading from a Text File

# Open a file for reading (mode 'r' means reading)
with open('filename.txt', 'r') as file:
    content = file.read()
    print(content)

Reading a File Line by Line

with open('filename.txt', 'r') as file:
    lines = file.readlines()
    for line in lines:
        print(line.strip())  # strip() removes newline characters

Reading a File One Line at a Time

with open('filename.txt', 'r') as file:
    while True:
        line = file.readline()
        if not line:
            break
        print(line.strip())

Example: Saving and Loading Encrypted Messages

Saving an Encrypted Message to a File

encrypted_message = "Gur pyrnare, gur dhvpx oebja sbk whzcf bire gur ynml qbt."

with open('encrypted_message.txt', 'w') as file:
    file.write(encrypted_message)

Loading an Encrypted Message from a File

with open('encrypted_message.txt', 'r') as file:
    encrypted_message = file.read()
    print("Loaded encrypted message:", encrypted_message)

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)
Back to top
Practice
Asymmetric crypto algorithms