Search code examples
pythonpython-3.xpython-cryptography

Self-signed certificate used when wrapping sockets


I'm trying to use a self-signed x509 certificate generated using the cryptography module in an ssl handshake. I'm generating the cert and key to PEM files as prescribed in the documentation and writing them to files using the following function:

def write_key_and_cert(self, certname="cert.pem", keyname="key.pem"):
    with open(certname, "wb") as f:
        f.write(self.cert.public_bytes(serialization.Encoding.PEM))
    with open(keyname, "wb") as f:

    f.write(self.private_key.private_bytes(encoding=serialization.Encoding.PEM,
                                           format=serialization.PrivateFormat.TraditionalOpenSSL,
                                           encryption_algorithm=serialization.BestAvailableEncryption(b"passphrase"),),)

The problem arises during the wrapping of the socket, the server is unable to use the certfile and keyfile, causing a hang. I believe it is due to the keyfile being encrypted (the ssl wrapping isn't decrypting the keyfile). Is there a way to use the cryptography module generated certfile/keyfile and, if so, how?


Solution

  • This problem was solved by creating the context and specifying the password when loading the cert chain:

    context = ssl.create_default_context()
    context.load_cert_chain(certfile=self.certfile, keyfile=self.keyfile, password=b"passphrase")
    

    This lets the ssl module do the decrypting of the keyfile and loading properly.