import socket
import threading
import base64
from cryptography.fernet import Fernet
# Class for handling encryption and decryption of messages
class EncryptingMessages:
def __init__(self):
self.key = Fernet.generate_key()
self.cipher_suite = Fernet(self.key)
print(self.key)
def encrypt_message(self, message):
encrypted_message = self.cipher_suite.encrypt(message.encode())
return base64.b64encode(encrypted_message).decode()
def decrypt_message(self, encrypted_message):
encrypted_message = base64.b64decode(encrypted_message.encode())
decrypted_message = self.cipher_suite.decrypt(encrypted_message).decode()
return decrypted_message
# Class for handling client connections
class ConnectionHandling:
def __init__(self, host, port, encrypting_messages):
self.host = host
self.port = port
self.encrypting_messages = encrypting_messages
self.server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.server_socket.bind((self.host, self.port))
self.server_socket.listen(5)
print(f"Server listening on {self.host}:{self.port}")
def handle_client(self, client_socket):
while True:
try:
encrypted_message = client_socket.recv(1024).decode()
if not encrypted_message:
break
decrypted_message = self.encrypting_messages.decrypt_message(encrypted_message)
print(f"Received: {decrypted_message}")
response = f"Echo: {decrypted_message}"
encrypted_response = self.encrypting_messages.encrypt_message(response)
client_socket.send(encrypted_response.encode())
except Exception as e:
print(f"Error: {e}")
break
client_socket.close()
def start(self):
try:
while True:
client_socket, addr = self.server_socket.accept()
print(f"Connection from {addr}")
client_handler = threading.Thread(target=self.handle_client, args=(client_socket,))
client_handler.start()
except KeyboardInterrupt:
print("Server interrupted. Shutting down...")
finally:
self.server_socket.close()
print("Server closed.")
# Main class to start the server
class Main:
def __init__(self, host='127.0.0.1', port=65432):
self.host = host
self.port = port
self.encrypting_messages = EncryptingMessages()
self.connection_handler = ConnectionHandling(self.host, self.port, self.encrypting_messages)
def run(self):
self.connection_handler.start()
if __name__ == "__main__":
server = Main()
server.run()
Assistant
Rewrite the encryption class to be more suffisticated and undecryptable, Also make the output layout : [Time] [Client, IP:PORT / Server] {Data or : for input}
To enhance the security of your server's encryption mechanism and improve the logging format, we'll implement the following changes:
Enhanced Encryption:
Asymmetric Encryption with RSA: We'll use RSA for encrypting and decrypting messages, making it more sophisticated and secure.
Hybrid Encryption Approach: Since RSA is not ideal for large messages, we'll combine RSA with symmetric encryption (Fernet). RSA will securely exchange a symmetric key, which will then be used for encrypting/decrypting the actual messages. This approach leverages the strengths of both encryption types.
Improved Logging Format:
All logs will follow the format: [Time] [Client IP:PORT / Server] {Data or Input}
This provides clear and structured logging for both server and client interactions.
Below is the revised code incorporating these enhancements:
python
import socket
import threading
import base64
from cryptography.hazmat.primitives.asymmetric import rsa, padding
from cryptography.hazmat.primitives import serialization, hashes
from cryptography.fernet import Fernet
from datetime import datetime
# Utility function for logging
def log_message(source, address, message):
current_time = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
source_label = "Server" if source == "server" else f"Client {address[0]}:{address[1]}"
print(f"[{current_time}] [{source_label}] {{ {message} }}")
# Class for handling encryption and decryption of messages
class EncryptingMessages:
def __init__(self):
# Generate RSA key pair
self.private_key = rsa.generate_private_key(
public_exponent=65537,
key_size=4096,
)
self.public_key = self.private_key.public_key()
self.fernet_key = Fernet.generate_key()
self.cipher_suite = Fernet(self.fernet_key)
log_message("server", (), "Encryption keys generated.")
self.print_keys()
def print_keys(self):
# For demonstration purposes. In production, securely distribute the public key.
public_pem = self.public_key.public_bytes(
encoding=serialization.Encoding.PEM,
format=serialization.PublicFormat.SubjectPublicKeyInfo
)
fernet_pem = self.fernet_key.decode()
log_message("server", (), f"Public RSA Key:\n{public_pem.decode()}")
log_message("server", (), f"Fernet Symmetric Key:\n{fernet_pem}")
def encrypt_symmetric_key(self, client_public_key_pem):
# Load client's public RSA key
client_public_key = serialization.load_pem_public_key(client_public_key_pem.encode())
# Encrypt the symmetric Fernet key with client's public RSA key
encrypted_fernet_key = client_public_key.encrypt(
self.fernet_key,
padding.OAEP(
mgf=padding.MGF1(algorithm=hashes.SHA256()),
algorithm=hashes.SHA256(),
label=None
)
)
return base64.b64encode(encrypted_fernet_key).decode()
def decrypt_symmetric_key(self, encrypted_symmetric_key):
# Decrypt the symmetric Fernet key with server's private RSA key
encrypted_key_bytes = base64.b64decode(encrypted_symmetric_key.encode())
decrypted_key = self.private_key.decrypt(
encrypted_key_bytes,
padding.OAEP(
mgf=padding.MGF1(algorithm=hashes.SHA256()),
algorithm=hashes.SHA256(),
label=None
)
)
self.cipher_suite = Fernet(decrypted_key)
log_message("server", (), "Symmetric key decrypted and cipher suite initialized.")
def encrypt_message(self, message):
encrypted_message = self.cipher_suite.encrypt(message.encode())
return base64.b64encode(encrypted_message).decode()
def decrypt_message(self, encrypted_message):
encrypted_bytes = base64.b64decode(encrypted_message.encode())
decrypted_message = self.cipher_suite.decrypt(encrypted_bytes).decode()
return decrypted_message
# Class for handling client connections
class ConnectionHandling:
def __init__(self, host, port, encrypting_messages):
self.host = host
self.port = port
self.encrypting_messages = encrypting_messages
self.server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.server_socket.bind((self.host, self.port))
self.server_socket.listen(5)
log_message("server", (), f"Server listening on {self.host}:{self.port}")
def handle_client(self, client_socket, addr):
try:
# Step 1: Exchange public keys
# Receive client's public RSA key
client_public_key_pem = client_socket.recv(4096).decode()
log_message("server", addr, "Received client's public RSA key.")
# Send server's public RSA key
server_public_pem = self.encrypting_messages.public_key.public_bytes(
encoding=serialization.Encoding.PEM,
format=serialization.PublicFormat.SubjectPublicKeyInfo
).decode()
client_socket.sendall(server_public_pem.encode())
log_message("server", addr, "Sent server's public RSA key.")
# Step 2: Receive encrypted symmetric key from client
encrypted_symmetric_key = client_socket.recv(4096).decode()
log_message("server", addr, "Received encrypted symmetric key from client.")
self.encrypting_messages.decrypt_symmetric_key(encrypted_symmetric_key)
# Communication loop
while True:
encrypted_message = client_socket.recv(4096).decode()
if not encrypted_message:
log_message("server", addr, "Client disconnected.")
break
decrypted_message = self.encrypting_messages.decrypt_message(encrypted_message)
log_message("server", addr, decrypted_message)
response = f"Echo: {decrypted_message}"
encrypted_response = self.encrypting_messages.encrypt_message(response)
client_socket.sendall(encrypted_response.encode())
log_message("server", addr, "Sent encrypted echo response.")
except Exception as e:
log_message("server", addr, f"Error: {e}")
finally:
client_socket.close()
def start(self):
try:
while True:
client_socket, addr = self.server_socket.accept()
log_message("server", addr, "Connection established.")
client_handler = threading.Thread(target=self.handle_client, args=(client_socket, addr))
client_handler.start()
except KeyboardInterrupt:
log_message("server", (), "Server interrupted. Shutting down...")
finally:
self.server_socket.close()
log_message("server", (), "Server closed.")
# Main class to start the server
class Main:
def __init__(self, host='127.0.0.1', port=65432):
self.host = host
self.port = port
self.encrypting_messages = EncryptingMessages()
self.connection_handler = ConnectionHandling(self.host, self.port, self.encrypting_messages)
def run(self):
self.connection_handler.start()
if __name__ == "__main__":
server = Main()
server.run()
Explanation of Changes
1. Enhanced Encryption with Hybrid Approach
RSA Key Pair Generation:
The EncryptingMessages class now generates an RSA key pair (private_key and public_key) upon initialization.
The server's public RSA key is printed out. In a real-world scenario, you'd securely distribute this to clients.
Symmetric Fernet Key Exchange:
A symmetric Fernet key is generated for encrypting and decrypting messages.
The encrypt_symmetric_key method allows encrypting this symmetric key using the client's public RSA key.
The decrypt_symmetric_key method decrypts the symmetric key received from the client using the server's private RSA key.
Message Encryption/Decryption:
Once the symmetric key is established, all messages are encrypted and decrypted using Fernet for efficiency and security.
Messages are base64-encoded to ensure safe transmission over sockets.
2. Improved Logging Format
A utility function log_message is created to handle all logging with the desired format:
code
[Time] [Client IP:PORT / Server] {Data or Input}
This function is used throughout the server to log key events such as connections, key exchanges, message transmissions, and errors.
3. Client Handler Enhancements
Key Exchange Protocol:
Upon a new client connection, the server expects to receive the client's public RSA key.
The server responds by sending its own public RSA key.
The client then sends the symmetric Fernet key encrypted with the server's public RSA key.
This symmetric key is decrypted by the server and used for subsequent message encryption/decryption.
Secure Communication:
All messages after the key exchange are encrypted using the established symmetric Fernet key, ensuring both confidentiality and integrity.
4. Handling Exceptions and Cleanup
The server gracefully handles exceptions, logs errors, and ensures that client sockets are closed properly in case of failures or disconnections.
Client Implementation
To complement the server's enhanced encryption mechanism, clients must perform corresponding steps:
Generate RSA Key Pair: Each client should generate its own RSA key pair.
Exchange Public Keys: Clients should send their public RSA key to the server and receive the server's public RSA key.
Encrypt Symmetric Key: Clients should encrypt a symmetric Fernet key with the server's public RSA key and send it to the server.
Secure Messaging: Use the symmetric Fernet key for encrypting and decrypting messages exchanged with the server.
Note: Implementing the client-side is essential for the complete functionality of this secure communication setup.
Security Considerations
Key Management: Ensure that private keys are stored securely and never transmitted over the network.
Public Key Distribution: Securely distribute public keys to prevent man-in-the-middle attacks.
Exception Handling: Be cautious with exception messages to avoid leaking sensitive information.
Production Deployment: For real-world applications, consider additional security measures such as certificate verification, authentication mechanisms, and using established protocols like TLS.
By implementing these changes, your server will have a more robust and secure encryption mechanism, and the logging will provide clear, timestamped records of all interactions.