PRACTICAL 9: OPENSSL IMPLEMENTATION

1. Open terminal as administrator.
2. Locate the bin folder of OpenSSL.
3. Run the command:

openssl req -x509 -newkey rsa:2048 -keyout key.pem -out cert.pem -days 365 -nodes

4. cert.pem and key.pem are created. Cut and paste them into the same folder as server.py and client.py.

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

All files (server.py, client.py, cert.pem, key.pem) should be in the same folder.
5. Run server.py.
6. Run client.py.
