Using the cert we just created…
February 12, 2010
In the last post, I described how to create a keypair and self-signed certificate. Now, we need to:
- use them to encrypt our traffic and
- allow the user to install the cert in his or her browser.
Here’s how to do this using Twisted. This code creates a page at 8080 that will download the certificate to the user’s browser and a site at 8081 that uses HTTPS. Connect to http://HOSTNAME:8080 to get the cert (your browser will prompt you to install it). Then, you can connect to https://HOSTNAME:8081 and browse securely.
Note that HOSTNAME can’t be ‘localhost’. Not much you can do here – certificates are tied to the actual hostname you use.
This code assumes that the code from that last post is in a module named pki.py, btw.
from twisted.web import server, resource, http
from twisted.internet import reactor, ssl
from twisted.python import log
import sys
from OpenSSL import SSL
from pki import KEY_FILE, CERT_FILE, create_self_signed_cert
def make_ssl_context():
create_self_signed_cert(".")
context = ssl.DefaultOpenSSLContextFactory(KEY_FILE, CERT_FILE)
return context
class HelloWorldPage(resource.Resource):
isLeaf = True
def render_GET(self, request):
return "<html><body><h1>Hello World</h1></body></html>"
class CertPage(resource.Resource):
isLeaf = True
def render_GET(self, request):
request.setHeader("Content-Type", "application/x-x509-ca-cert")
cert = open(CERT_FILE, 'rb').read()
request.write(cert)
request.finish()
return server.NOT_DONE_YET
log.startLogging(sys.stdout)
context = make_ssl_context()
cert_site = server.Site(CertPage())
site = server.Site(HelloWorldPage())
reactor.listenTCP(8080, cert_site)
reactor.listenSSL(8081, site, contextFactory = context)
reactor.run()
Advertisement