title: How can I do certificate pinning for TLS sockets in python 2.7?
body: <p>I have a python TLS server using a self signed certificate.  That works.  The code looks like this for now:</p>
  
  <pre><code>#!/usr/bin/python
  
  import socket, ssl
  
  context = ssl.create_default_context(ssl.Purpose.CLIENT_AUTH)
  context.load_cert_chain(certfile="server.crt", keyfile="server.key")
  
  bindsocket = socket.socket()
  bindsocket.bind(('127.0.0.1', 8888))
  bindsocket.listen(5)
  
  while True:
      newsocket, fromaddr = bindsocket.accept()
      connstream = context.wrap_socket(newsocket, server_side=True)
      try:
          print("Got connection!")
      finally:
          connstream.shutdown(socket.SHUT_RDWR)
          connstream.close()
  </code></pre>
  
  <p>I am now trying to make a client in python that connects to this server.  On the first connection attempt, I'd like to retrieve either the public key, or a hash of the public key, and then verify this on all future connections.  How can I do with with python and the ssl package?</p>
  
  <p>This is the code I'm playing with:</p>
  
  <pre><code>#!/usr/bin/python
  
  import ssl, socket, pprint
  
  context = ssl.SSLContext(ssl.PROTOCOL_TLS)
  context.verify_mode = ssl.CERT_REQUIRED
  context.check_hostname = False
  
  
  cnx = context.wrap_socket(socket.socket(socket.AF_INET), certfile="server.crt")
  cnx.connect(('127.0.0.1', 8888))
  pprint.pprint(cnx.getpeercert())
  </code></pre>
  
  <p>As it stands right now, it fails because there is no certificate chain to verify the cert.  I don't care about that, though.  All I care about is that the server I'm talking to has the private key that matches the public key.  What do I do?</p>