PRACTICAL NO: 9
OPENSSL IMPLEMENTATION

STEP 1: Open Terminal as Administrator.

STEP 2: Locate the bin folder of OpenSSL.

STEP 3: Run the following command:
openssl req -x509 -newkey rsa:2048 -keyout key.pem -out cert.pem -days 365 -nodes

STEP 4: The cert.pem and key.pem files are created. Cut and paste both files into the same folder where server.py and client.py are located.

SERVER CODE (server.py):
import socket
import ssl

host = 'localhost'
port = 8443
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.bind((host, port))
sock.listen(5)
print(f"[*] Listening on https://{host}:{port}")
context = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER)
context.load_cert_chain(certfile="cert.pem", keyfile="key.pem")
while True:
    client_socket, addr = sock.accept()
    print(f"[+] Connection from {addr}")
    with context.wrap_socket(client_socket, server_side=True) as ssock:
        data = ssock.recv(1024).decode()
        print("[Client says]:", data)
        ssock.sendall(b"Hello from secure server!")

CLIENT CODE (client.py):
import socket
import ssl

hostname = "localhost"
port = 8443
context = ssl.create_default_context()
context.check_hostname = False
context.verify_mode = ssl.CERT_NONE  # Allow self-signed certs
with socket.create_connection((hostname, port)) as sock:
    with context.wrap_socket(sock, server_hostname=hostname) as ssock:
        ssock.sendall(b"Hello secure server!")
        print("[Server says]:", ssock.recv(1024).decode())

STEP 5: Keep all four files (server.py, client.py, cert.pem, and key.pem) in the same folder.

STEP 6: Run server.py.

STEP 7: Run client.py.
