Free cookie consent management tool by TermsFeed The load_cert_chain() method of SSLContext class in Python | Pythontic.com

The load_cert_chain() method of SSLContext class in Python

Method Name:

load_cert_chain

Method Signature:

load_cert_chain(certfile, keyfile=None, password=None)

Parameters:

certfile            - Path of the X.509 certificate file in PEM(Privacy Enhanced Email) format.

keyfile              - The private key of the certificate

password            - Password for the private key if the private key is encrypted. The value to this parameter can be a strbytes or bytearray or a function returning str, bytes or bytearray.

Return value:

None

Overview:

  • The method load_cert_chain() loads an X.509 certificate and its private key into the SSLContext object.
  • The loaded certificate will be used during the TLS/SSL handshake with the peer.

Example:

This SSL Client program can be used along with the SSL Server program provided in the Introduction to the SSLSocket in Python.

# Example Python program that uses SSLContext.load_cert_chain()
# to load the client certificate into the SSLContext
# and proceeds with the SSL Handshake and other operations
import socket
import ssl

# Server IP and Port details
sslServerIP         = "127.0.0.1"
sslServerPort       = 15001

# Construction of an SSLContext
sslSettings                    = ssl.create_default_context()
sslSettings.check_hostname    = True

# Loading of CA certificate.
# With this CA certificate this client will validate certificate 
# from the server
sslSettings.load_verify_locations("./DemoCA.pem")

# Ease the policy of Python3.13 towards self-signed certificates
sslSettings.verify_flags = sslSettings.verify_flags & ~ssl.VERIFY_X509_STRICT

# Loading of client certificate
sslSettings.load_cert_chain(certfile = "./DemoClt1.pem", 
                            keyfile = "./DemoClt1.key")

# Create a stream based client socket
clientSocket        = socket.socket()

# Make the client socket suitable for secure communication
tlsSocket  = sslSettings.wrap_socket(clientSocket,
                                     server_hostname = "DemoServer",
                                     server_side = False)
tlsSocket.connect((sslServerIP, sslServerPort))

# Obtain the certificate from the server
server_cert = tlsSocket.getpeercert()
print("The server certificate is not valid before:")
print(server_cert["notBefore"])

print("The server certificate is not valid after:")
print(server_cert["notAfter"])

Output:

The server certificate is not valid before:
Sep 22 10:44:04 2025 GMT
The server certificate is not valid after:
Sep 22 10:44:04 2026 GMT


Copyright 2025 © pythontic.com