Search code examples
pythonsocketsencryptionaesmessaging

A Question about Encryption in python with sockets


I have a basic Server and a Client Setup

How do I:

If I am using AES encryption with the standard library given with python. Will I have to already "Hard-Code" the encryption key in both of the codes or is there a way to randomly refresh a key without "Hard-coding" it and keeping it the same on both sides? If yes, how?

Because in an other thread Sending Encrypted strings using socket in Python They had given the encryption key on both sides of the connection...

SERVER.py:

import socket

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind(("IP", 1234))
s.listen(5)

while True:
    clientsocket, address = s.accept()
    print(f"Connection from {address} established!")
    clientsocket.send(bytes("Hello World!", "utf-8"))

CLIENT.py:

import socket

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect(("IP", 1234))
msg = s.recv(1024)
print(msg.decode("utf-8"))

Solution

  • AES is only about encryption with a fixed key, not about key management. Based on your example it looks like you actually want to protect the socket based communication between two parties. Please use TLS for this - it is an well established protocol for this purpose (base for HTTPS) which cares about authentication, encryption, key management, ...

    It is strongly recommended to use such established solutions instead of building your own, since the latter is easily to get wrong. For example the thread you reference is using AES in plain CBC mode which does not provide any integrity. This means a man in the middle attacker can change the encrypted data without the communication peers being able to detect such modification. TLS cares about all of this properly by default.