0

I am trying to encrypt a python socket. I have the below code that is able to send a message from the client to the server. I am wondering how I can implement some sort of encryption to secure the connection.

I know that I could encrypt the data on the client, then send the encrypted message over the existing socket to the server to then be decrypted on the server using a secret key or passphrase, but that's not what I'm trying to do.

I know that when you visit a website that has https enabled, your unencrypted data is sent through a secure tunnel that can't be viewed by a MITM attack. I'm trying to do the same thing but with a python socket and I'm wondering how to implement this if it's at all possibe.

I'm very new to python, so any help from external resources to a full code example would be greatly appreciated

server:
import socket 
import threading

HEADER = 64
PORT = 5050
SERVER = "*Server IP*"
ADDR = (SERVER, PORT)
FORMAT = 'utf-8'
DISCONNECT_MESSAGE = "!DISCONNECT"

server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server.bind(ADDR)

def handle_client(conn, addr):
    print(f"[NEW CONNECTION] {addr} connected.")

    connected = True
    while connected:
        msg_length = conn.recv(HEADER).decode(FORMAT)
        if msg_length:
            msg_length = int(msg_length)
            msg = conn.recv(msg_length).decode(FORMAT)
            if msg == DISCONNECT_MESSAGE:
                connected = False

            print(f"[{addr}] {msg}")
            conn.send("Msg received".encode(FORMAT))

    conn.close()


def start():
    server.listen()
    print(f"[LISTENING] Server is listening on {SERVER}")
    while True:
        conn, addr = server.accept()
        thread = threading.Thread(target=handle_client, args=(conn, addr))
        thread.start()
        print(f"[ACTIVE CONNECTIONS] {threading.activeCount() - 1}")


print("[STARTING] server is starting...")
start()

Client:

import socket

HEADER = 64
PORT = 5050
FORMAT = 'utf-8'
DISCONNECT_MESSAGE = "!DISCONNECT"
SERVER = "*Server IP*"
ADDR = (SERVER, PORT)

client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
client.connect(ADDR)

def send(msg):
    message = msg.encode(FORMAT)
    msg_length = len(message)
    send_length = str(msg_length).encode(FORMAT)
    send_length += b' ' * (HEADER - len(send_length))
    client.send(send_length)
    client.send(message)
    print(client.recv(2048).decode(FORMAT))

user_input = None
while user_input != "exit":
    user_input = (input())
    send(user_input)


send(DISCONNECT_MESSAGE)
2

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.