Implementing Secure File Transfer with Python Sockets and XOR Encryption
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
- Server starts and binds to port 8080
- Server listens with maximum 5 queued connections
- Client connects using server IP and port
- Client reads plaintext from file
- Client applies XOR encryption with key 666
- Client sends encrypted data to server
- Server receives and decrypts using same key
- 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.