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 string, bytes or bytearray or a function returning string, 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 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.SSLContext();

sslSettings.verify_mode         = ssl.CERT_REQUIRED;

 

# Loading of CA certificate.

# With this CA certificate this client will validate certificate from the server

sslSettings.load_verify_locations("./DemoCA.pem")

 

# Loading of client certificate

sslSettings.load_cert_chain(certfile="./DemoClt.crt", keyfile="./DemoClt.key")

 

# Create a stream based client socket

clientSocket        = socket.socket();

 

# Make the client socket suitable for secure communication

tlsSocket  = sslSettings.wrap_socket(clientSocket);

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:

Apr  2 12:12:33 2020 GMT

The server certificate is not valid after:

Apr  1 12:12:33 2025 GMT


Copyright 2024 © pythontic.com