Getting certificate chain with Python 3.3 SSL module

后端 未结 3 865
萌比男神i
萌比男神i 2021-01-12 04:53

I can get the standard certificate information for an SSL connection in Python 3.3 via the getpeercert() method on the SSL socket. However, it doesn\'t seem to provide the c

3条回答
  •  执笔经年
    2021-01-12 05:34

    The answer above did not work out of the box.

    After going through many options, I found this to be the simplest approach which requires minimum 3rd party libraries.

    pip install pyopenssl certifi

    import socket
    from OpenSSL import SSL
    import certifi
    
    hostname = 'www.google.com'
    port = 443
    
    
    context = SSL.Context(method=SSL.TLSv1_METHOD)
    context.load_verify_locations(cafile=certifi.where())
    
    conn = SSL.Connection(context, socket=socket.socket(socket.AF_INET, socket.SOCK_STREAM))
    conn.settimeout(5)
    conn.connect((hostname, port))
    conn.setblocking(1)
    conn.do_handshake()
    conn.set_tlsext_host_name(hostname.encode())
    for (idx, cert) in enumerate(conn.get_peer_cert_chain()):
        print(f'{idx} subject: {cert.get_subject()}')
        print(f'  issuer: {cert.get_issuer()})')
        print(f'  fingerprint: {cert.digest("sha1")}')
    
    conn.close()
    

    Here is a link to the original idea https://gist.github.com/brandond/f3d28734a40c49833176207b17a44786

    Here is a reference which brought me here How to get response SSL certificate from requests in python?

提交回复
热议问题