[Python] How do I achieve Python TCP Socket Client/Server with Communications Encrypted?

Discussão em 'Python' iniciado por Stack, Junho 17, 2025.

  1. Stack

    Stack Membro Participativo

    Backstory: what I have done

    {Codes at the bottom} I've already coded the multithreaded client and server programs using python socket, with the help of the following sites:

    Regarding Encryption & Decryption


    (1) Exactly at what places in my codes should I encrypt/decrypt my message? Do I encrypt the messages themselves after the user inputs or do I encrypt the byte streams after the input messages have been encoded?

    (2) And how am I supposed to encrypt/decrypt the communication properly and efficiently? (It'd be nice to see code solutions with explanation, many thanks)
    ​
    My Codes Currently


    _server.py

    import socket
    import os
    from _thread import *
    import struct # Here to convert Python data types into byte streams (in string) and back

    # ---- To Avoid Message Boundary Problem on top of TCP protocol ----
    def send_msg(sock: socket, msg): # ---- Use this to send
    # Prefix each message with a 4-byte length (network byte order)
    msg = struct.pack('>I', len(msg)) + msg
    sock.sendall(msg)

    def recv_msg(sock: socket): # ---- Use this to receive
    # Read message length and unpack it into an integer
    raw_msglen = recvall(sock, 4)
    if not raw_msglen:
    return None
    msglen = struct.unpack('>I', raw_msglen)[0]
    # Read the message data
    return recvall(sock, msglen)

    def recvall(sock: socket, n: int):
    # Helper function to receive n bytes or return None if EOF is hit
    data = bytearray()
    while len(data) < n:
    packet = sock.recv(n - len(data))
    if not packet:
    return None
    data.extend(packet)
    return data

    # ---- Server Communication Setup

    HOST = '127.0.0.1' # Standard loopback interface address (localhost)
    PORT = 65432 # Port to listen on (non-privileged ports are > 1023)
    ThreadCount = 0

    try: # create socket
    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    print ("Socket successfully created")
    except socket.error as err:
    print ("socket creation failed with error %s" %(err))

    try: # bind socket to an address
    s.bind((HOST, PORT))
    except socket.error as e:
    print(str(e))

    print('Waitiing for a Connection..')
    s.listen(3)

    def threaded_client(conn: socket):
    conn.send(str.encode('Welcome to the Server'))
    while True:
    # data = conn.recv(2048) # receive message from client
    data = recv_msg(conn)
    reply = 'Server Says: ' + data.decode('utf-8')
    if not data:
    break
    # conn.sendall(str.encode(reply))
    send_msg(conn, str.encode(reply))
    conn.close()

    while True:
    Client, addr = s.accept()
    print('Connected to: ' + addr[0] + ':' + str(addr[1]))
    start_new_thread(threaded_client, (Client, )) # Calling threaded_client() on a new thread
    ThreadCount += 1
    print('Thread Number: ' + str(ThreadCount))
    s.close()


    _client.py

    import socket
    import struct # Here to convert Python data types into byte streams (in string) and back

    # ---- To Avoid Message Boundary Problem on top of TCP protocol ----
    def send_msg(sock: socket, msg): # ---- Use this to send
    # Prefix each message with a 4-byte length (network byte order)
    msg = struct.pack('>I', len(msg)) + msg
    sock.sendall(msg)

    def recv_msg(sock: socket): # ---- Use this to receive
    # Read message length and unpack it into an integer
    raw_msglen = recvall(sock, 4)
    if not raw_msglen:
    return None
    msglen = struct.unpack('>I', raw_msglen)[0]
    # Read the message data
    return recvall(sock, msglen)

    def recvall(sock: socket, n: int):
    # Helper function to receive n bytes or return None if EOF is hit
    data = bytearray()
    while len(data) < n:
    packet = sock.recv(n - len(data))
    if not packet:
    return None
    data.extend(packet)
    return data

    # ---- Client Communication Setup ----

    HOST = '127.0.0.1' # The server's hostname or IP address
    PORT = 65432 # The port used by the server

    try:
    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    print ("Socket successfully created")
    except socket.error as err:
    print ("socket creation failed with error %s" %(err))

    print('Waiting for connection')
    try:
    s.connect((HOST, PORT))
    except socket.error as e:
    print(str(e))

    Response = s.recv(1024)
    while True:
    Input = input('Say Something: ')
    # s.send(str.encode(Input))
    send_msg(s, str.encode(Input))
    # Response = s.recv(1024)
    Response = recv_msg(s)
    print(Response.decode('utf-8'))

    s.close()

    Continue reading...

Compartilhe esta Página