Getpeercert Method Of SSLSocket Class

Method Name:


Method Signature:



binary_form – Boolean value that determines the form in which the certificate is returned.  If True is passed, the certificate is returned as a Python dictionary. If False is passed, the certificate is returned in DER binary format as a Python string.


Return Value:

  • If a certificate is available at the other end of the communication, a Python dictionary containing certificate information or a Python string in DER format is returned.
  • The format of the returned certificate is based on the value passed to the binary_form parameter.



  • ValueError, if the call precedes the SSL handshake.


  • The method getpeercert() retrieves the digital certificate available if any, from the other end of the communication.
  • The retrieved certificate is in the form of a Python dictionary if the parameter binary_form is False. Otherwise, the certificate is in the DER binary format. A certificate in DER format can be converted to human readable PEM format using the function der_cert_to_pem_cert(). Similarly a certificate in PEM format can be converted to DER format using the function pem_cert_to_der_cert().


# Example Python program that uses a client socket to

# connect to a server and ask for the server's

# certificate

import socket

import ssl

import platform


# Create an SSL context

sslContext              = ssl.SSLContext();

sslContext.verify_mode  = ssl.CERT_REQUIRED;


# Check for OS X platform

if platform.system().lower() == 'darwin':

    import certifi

    import os


    # Load the CA certificates used for validating the peer's certificate






# Create a client socket

clientSocket        = socket.socket();


# Get an instance of SSLSocket

secureClientSocket  = sslContext.wrap_socket(clientSocket);


# Get the SSL certificate of the peer

secureClientSocket.connect(("", 443));


serverCert = secureClientSocket.getpeercert();

print("Certificate obtained from the server:");




Certificate obtained from the server:

{'subject': ((('countryName', 'US'),), (('stateOrProvinceName', 'California'),), (('localityName', 'Los Angeles'),), (('organizationName', 'Internet Corporation for Assigned Names and Numbers'),), (('organizationalUnitName', 'Technology'),), (('commonName', ''),)), 'issuer': ((('countryName', 'US'),), (('organizationName', 'DigiCert Inc'),), (('commonName', 'DigiCert SHA2 Secure Server CA'),)), 'version': 3, 'serialNumber': '0FD078DD48F1A2BD4D0F2BA96B6038FE', 'notBefore': 'Nov 28 00:00:00 2018 GMT', 'notAfter': 'Dec  2 12:00:00 2020 GMT', 'subjectAltName': (('DNS', ''), ('DNS', ''), ('DNS', ''), ('DNS', ''), ('DNS', ''), ('DNS', ''), ('DNS', ''), ('DNS', '')), 'OCSP': ('',), 'caIssuers': ('',), 'crlDistributionPoints': ('', '')}


Copyright 2022 ©