Fading Coder

One Final Commit for the Last Sprint

Home > Tech > Content

Implementing Secure File Transfer with Python Sockets and XOR Encryption

Tech May 13 2

Server Implementation

The server establishes a TCP socket and listens for incoming client connections on a specified IP address and port.

import socket

def xor_cipher(text, key):
    """XOR-based encryption and decryption function."""
    result = []
    for char in text:
        result.append(chr(ord(char) ^ key))
    return ''.join(result)

# Create server socket
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server.bind(('0.0.0.0', 8080))
server.listen(5)
print(f"Server listening on port 8080")

# Accept client connection
client_conn, client_addr = server.accept()
print(f"Connection established from {client_addr}")

while True:
    # Receive encrypted data
    encrypted_data = client_conn.recv(4096)
    if not encrypted_data:
        break
    
    # Decode and decrypt
    decoded_data = encrypted_data.decode('utf-8')
    decrypted_data = xor_cipher(decoded_data, 666)
    
    # Write to file
    with open('received_message.txt', 'w', encoding='utf-8') as f:
        f.write(decrypted_data)
    
    print(f"Decrypted message: {decrypted_data}")

client_conn.close()
server.close()

Client Implementation

The client reads data from a file, encrypts it using XOR cipher, and transmits to the server.

import socket

def xor_cipher(text, key):
    """XOR-based encryption and decryption function."""
    result = []
    for char in text:
        result.append(chr(ord(char) ^ key))
    return ''.join(result)

# Prepare file content
source_file = 'message.txt'
with open(source_file, 'w', encoding='utf-8') as f:
    f.write('Hello, World!')

# Create client socket
client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
client.connect(('192.168.5.3', 8080))

# Read file content
with open(source_file, 'r', encoding='utf-8') as f:
    plaintext = f.read()

# Encrypt using XOR cipher
encrypted = xor_cipher(plaintext, 666)

# Send to server
client.send(encrypted.encode('utf-8'))

client.close()

XOR Cipher Algorithm

The XOR cipher operates on the principle that applying the same operation twice restores the original value. For each character:

def xor_cipher(text, key):
    result = []
    for char in text:
        # ord() converts character to Unicode code point
        # XOR with key
        # chr() converts back to character
        result.append(chr(ord(char) ^ key))
    return ''.join(result)

This function serves both encryption and decryption since char ^ key ^ key == char.

File Operations

Reading Files

# Read entire file
content = open('file.txt', 'r').read()

# Read line by line
with open('file.txt', 'r') as f:
    for line in f:
        process(line)

Writing Files

# Write with overwrite mode
with open('output.txt', 'w') as f:
    f.write('new content')

# Append mode
with open('output.txt', 'a') as f:
    f.write('additional content')

Communication Flow

  1. Server starts and binds to port 8080
  2. Server listens with maximum 5 queued connections
  3. Client connects using server IP and port
  4. Client reads plaintext from file
  5. Client applies XOR encryption with key 666
  6. Client sends encrypted data to server
  7. Server receives and decrypts using same key
  8. Server writes decrypted content to file

Common Issues and Solutions

Firewall blocking connections

Ensure firewall rules allow traffic on the designated port or disable firewall during development.

Incorrect byte-to-string conversion

Always use .decode() method when converting bytes to strings. Using str() on bytes producse an undesirable representation:

# Correct method
text = byte_data.decode('utf-8')

# Incorrect method (produces "b'...'" string)
text = str(byte_data)

Connection closure detection

Server detects client disconnection when recv() returns empty bytes (`b''`). The server should break the loop and close the connection upon receiving empty data.

Tags: Python

Related Articles

Understanding Strong and Weak References in Java

Strong References Strong reference are the most prevalent type of object referencing in Java. When an object has a strong reference pointing to it, the garbage collector will not reclaim its memory. F...

Comprehensive Guide to SSTI Explained with Payload Bypass Techniques

Introduction Server-Side Template Injection (SSTI) is a vulnerability in web applications where user input is improper handled within the template engine and executed on the server. This exploit can r...

Implement Image Upload Functionality for Django Integrated TinyMCE Editor

Django’s Admin panel is highly user-friendly, and pairing it with TinyMCE, an effective rich text editor, simplifies content management significantly. Combining the two is particular useful for bloggi...

Leave a Comment

Anonymous

◎Feel free to join the discussion and share your thoughts.