PRACTICAL 9: OPENSSL IMPLEMENTATION

Server code:

import socket, ssl

ctx = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER)
ctx.load_cert_chain("cert.pem", "key.pem")

with socket.create_server(("localhost", 8443)) as sock:
    print("[*] Listening on https://localhost:8443")
    while True:
        conn, addr = sock.accept()
        print(f"[+] Connection from {addr}")
        with ctx.wrap_socket(conn, server_side=True) as s:
            print("[Client says]:", s.recv(1024).decode())
            s.sendall(b"Hello from secure server!")

Client code:

import socket, ssl

ctx = ssl._create_unverified_context()

with ctx.wrap_socket(socket.create_connection(("localhost", 8443)),
                    server_hostname="localhost") as s:
    s.sendall(b"Hello secure server!")
    print("[Server says]:", s.recv(1024).decode())
