Skip to content

Instantly share code, notes, and snippets.

@themorgantown
Created June 14, 2024 19:57
Show Gist options
  • Save themorgantown/ad592aad05e29d0d69394daa4342447d to your computer and use it in GitHub Desktop.
Save themorgantown/ad592aad05e29d0d69394daa4342447d to your computer and use it in GitHub Desktop.
ssl on localhost bing badda boom - mkcert version: https://gist.github.com/themorgantown/1f68ad2230480c51e6621c7d82db57cc
import http.server
import ssl
import socket
import os
import subprocess
HOST = f"{socket.gethostname()}"
PORT = 443
CERT_FILE = 'self-signed.cert'
KEY_FILE = 'self-signed.key'
os.chdir(os.path.join(os.path.expanduser('~'), 'Desktop', 'document'))
if not os.path.exists(CERT_FILE) or not os.path.exists(KEY_FILE):
print("Generating self-signed SSL certificate...")
subject = f"/CN={HOST}"
os.system(f"openssl req -x509 -newkey rsa:4096 -nodes -keyout {KEY_FILE} -out {CERT_FILE} -days 365 -subj '{subject}'")
# Add hostname to /etc/hosts if not already present
hosts_entry = f"127.0.0.1 {HOST}"
with open("/etc/hosts", "r") as f:
hosts_content = f.read()
if hosts_entry not in hosts_content:
subprocess.run(["sudo", "-n", "/usr/bin/tee", "-a", "/etc/hosts"], input=bytes(hosts_entry, "utf-8"), shell=False)
httpd = http.server.HTTPServer((HOST, PORT), http.server.SimpleHTTPRequestHandler)
context = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER)
context.load_cert_chain(CERT_FILE, KEY_FILE)
httpd.socket = context.wrap_socket(httpd.socket, server_side=True)
print(f"Serving on https://{HOST}:{PORT} (You may need to accept the self-signed certificate)")
try:
httpd.serve_forever()
except KeyboardInterrupt:
httpd.server_close()
print("\nServer stopped.")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment