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())


NOTE: Keep the server and client code in separate files (server.py and client.py).
Place cert.pem and key.pem in the same folder. Start server.py first, then client.py.
