Load_verify_locations method of SSLContext class in Python

Method Name:

load_verify_locations

Method Signature:

load_verify_locations(cafile=None, capath=None, cadata=None)

Parameters:

cafile – File path for file containing the CA Certtificate(s)

capath – Path for the directory containing the CA Certtificate(s)

cadata – The certificate data in PEM or DER format.

Return Value:

None

Overview:

  • The method load_verify_locations() of the SSLContext class loads a set of CA certificates used for verifying the certificate of the peer.
  • The CA certificates are the certificates of Certifying Authorities. Usually, a Certifying Authority designates the work of issuing the certificates to a set of (sub-) authorities and each of such authorities again delegating to another (sub-)set of authorities forming a CA chain.
  • While validating a peer’s certificate, one or more certificates in the CA chain are validated by a host.

Example:

# Example Python program that uses SSLContext.load_verify_locations()

# to load and verify one or more CA certificates

import socket

import ssl

import os

import time

 

# IP address and port number

ipAddress   = "127.0.0.1";

portNumber  = 15001;

 

# SSLContext construction

sslSettings                     = ssl.SSLContext();

sslSettings.verify_mode         = ssl.CERT_REQUIRED;

 

# Load a CA certificate.

# The CA certificate The will be used to validate the certificate from the server

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

 

# Loading of client certificate which will be validated by the server

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

 

# Streaming socket

s = socket.socket();

 

# Obtain SSLSocket instance

ss  = sslSettings.wrap_socket(s);

 

# Get rid of the original socket

s.close();

 

# Connect to the server

ss.connect((ipAddress, portNumber));

 

# Print the loaded certificate statistics

print("Certificates currently loaded into the SSLContext");

print(sslSettings.cert_store_stats());

 

# Send a message to the server

ss.sendall("Hello Server!".encode());

 

# Receive time from server

dataFromServer = ss.recv(1024);

 

print("Message received from the server");

print(dataFromServer);   

  

# Close the secure socket

ss.close();   

 

Output:

Certificates currently loaded into the SSLContext:

{'x509': 1, 'crl': 0, 'x509_ca': 1}

Message received from the server:

b'2020-04-16 19:07:57.620855'


Copyright 2024 © pythontic.com