Search code examples
pythonssldigital-signaturex509verification

Where to get name of signature algorithm from SSLSocket?


I could not find a suitable way to get the name of the signature algorithm used for a certificate that is received by an SSLSocket. I'm aware you can pull the bytes of the peer's cert with SSLSocket.getpeercert(True) but I don't know what to do with it past that. PyOpenSSL doesn't seem to have an easy interface to load an X509 from it's byte content.

I would like to know this information as certificates with SHA1 are not allowed to have expiration times after January 1st, 2017 and this is not checked by Python's SSLSocket.do_handshake() implementation.


Solution

  • After the very helpful comment pointing me in the right direction, you can use the cryptography module to load the DER X509 format that the SSLSocket.getpeercert() function outputs. From this Certificate instance you can also access many other fields about the certificate such as expiration time. Here is the way that I am doing it right now:

    import cryptography.x509
    import cryptography.hazmat.backends.openssl
    import ssl
    sock = ssl.SSLSocket()
    
    # Wrap a socket, connect, handshake, etc etc...
    
    cert = cryptography.x509.load_der_x509_certificate(
        sock.getpeercert(True),
        cryptography.hazmat.backends.openssl.backend
    )
    print(cert.signature_hash_algorithm.name) # This prints "sha1".