Exploring SSL Certificate Verification with Python


In our daily internet usage, security is of paramount importance when communicating online. Especially when exchanging data between websites, it is crucial to ensure that our information is secure. One way to achieve this security is by using SSL (Secure Sockets Layer) certificates. In this article, we will explore what SSL certificates are, why they are important, and how we can write our own SSL verification tool using Python.

Learning Objectives:

  1. What is SSL and why is it important?
  2. How can we check SSL certificates using Python?
  3. How can we use a simple Python tool to check the SSL certificate of a website?

What is SSL and Why is it Important?

SSL (Secure Sockets Layer) is a cryptographic protocol used to ensure secure communication between computers. This technology encrypts data during transmission, preventing third parties from accessing it. SSL is used to ensure confidentiality, integrity, and security in communication over the internet(PathFinder: Web Path Finder).

Why is it Important?

  1. Data Security: SSL encrypts data during transmission, ensuring that data exchanged over the internet is secure and protected from unauthorized access or theft by malicious parties.
  2. Identity Authentication: SSL certificates authenticate the identity of a website. This allows users to verify that the website they are visiting is indeed the one they intended to visit. SSL certificates are signed by trusted authorities recognized by web browsers, and these authorities employ various validation processes to verify the identity of the website.
  3. SEO Impact: Search engines encourage the use of SSL and prefer websites that use the HTTPS protocol. Therefore, using an SSL certificate can improve a website’s search engine ranking.
  4. Customer Trust: Using SSL inspires trust in website visitors. Users may avoid shopping from websites that lack an SSL certificate or display security warnings. Providing a secure connection increases trust in your website and encourages more interaction from visitors.
  5. Data Integrity: SSL ensures the integrity of transmitted data. It verifies whether data has been altered during transmission and ensures that the data received by the recipient remains unchanged from its original form(Securing with OpenSSL: Essential Usage and Commands).

SSL certificates are a fundamental aspect of internet security and are widely used to ensure the security of online communication. Having an SSL certificate for a website ensures that users’ data is protected, enhancing the credibility of the website.

Writing Our Own SSL Verification Tool with Python

Python offers several libraries that we can utilize to check SSL certificates. In this article, we’ll learn how to check a website’s SSL certificate using Python’s ssl and socket modules. Additionally, we’ll use the colorama library to obtain colorized output.

1. Importing Required Modules:

import ssl
import socket
import datetime
from colorama import Fore, Style

These lines import the necessary Python modules. While the ssl and socket modules are used to check SSL certificates, the datetime module is used to process certificate dates. The colorama module is used to obtain colorized output.

2. CertificateChecker Class:

class CertificateChecker:
    def __init__(self, hostname):
        self.hostname = hostname

This class is used to check the SSL certificate of a specified hostname. The __init__ method is the class constructor and takes a hostname parameter.

3. get_certificate_info Method:

    def get_certificate_info(self):
        # Create an SSL context
        context = ssl.create_default_context()

        # Establish a connection to the specified host and port
        with socket.create_connection((self.hostname, 443)) as sock:
            # Wrap the socket with SSL/TLS
            with context.wrap_socket(sock, server_hostname=self.hostname) as ssock:
                # Retrieve the peer's certificate
                cert = ssock.getpeercert()

                # Extract subject and issuer information from the certificate
                subject = dict(item[0] for item in cert['subject'])
                issuer = dict(item[0] for item in cert['issuer'])

                # Convert validity dates from string to datetime objects
                valid_from = datetime.datetime.strptime(cert['notBefore'], "%b %d %H:%M:%S %Y GMT")
                valid_to = datetime.datetime.strptime(cert['notAfter'], "%b %d %H:%M:%S %Y GMT")

                # Return the certificate information as a dictionary
                return {
                    'subject': subject,
                    'issuer': issuer,
                    'valid_from': valid_from,
                    'valid_to': valid_to

This method retrieves the SSL certificate of the specified hostname. It first creates an SSL context using ssl.create_default_context(). Then, it establishes a connection to the specified host and port using socket.create_connection(). After that, it wraps the socket with SSL/TLS using context.wrap_socket() to initiate the secure connection. Once the secure connection is established, it retrieves the peer’s certificate using ssock.getpeercert().

4. print_certificate_info Method:

    def print_certificate_info(self):
            # Get certificate information using the get_certificate_info method
            cert_info = self.get_certificate_info()

            # Print certificate information with colorized output
            print(f"\n{Fore.GREEN}Certificate Information:{Style.RESET_ALL}")

            # Print subject information
            for key, value in cert_info['subject'].items():
                print(f"\t* {key}: {value}")

            # Print issuer information
            for key, value in cert_info['issuer'].items():
                print(f"\t* {key}: {value}")

            # Print validity start date
            print(f"{Fore.CYAN}Validity Start Date:{Style.RESET_ALL} {cert_info['valid_from']}")

            # Print validity end date
            print(f"{Fore.CYAN}Validity End Date  :{Style.RESET_ALL} {cert_info['valid_to']}")

        # Handle any exceptions that may occur during the process
        except Exception as e:
            # Print error message in red color
            print(f"{Fore.RED}Error: {e}{Style.RESET_ALL}")

This method prints the SSL certificate information to the console. It first retrieves the certificate information using the get_certificate_info() method. Then, it prints the certificate information with colorized output using the colorama library(Python in Cybersecurity: Exploring Popular Modules).

  • The certificate information is printed with a green-colored header.
  • The subject and issuer information are printed with cyan color.
  • The validity start date and end date are also printed with cyan color.

Any exceptions that occur during the process are caught and an error message is printed in red color.

5. main Function:

def main():
    # Prompt the user to enter a website address
    hostname = input("Please enter the website address you want to query (e.g., ")

    # Create a CertificateChecker object with the provided hostname
    checker = CertificateChecker(hostname)

    # Print the certificate information using the print_certificate_info method

if __name__ == "__main__":

This function serves as the entry point of the program. It prompts the user to enter a website address and creates a CertificateChecker object with the provided hostname. Then, it calls the print_certificate_info method of the CertificateChecker object to print the SSL certificate information to the console. If the script is executed directly (not imported as a module), the main() function is called to start the program.


In this article, we explored the importance of SSL certificates and how they work. Additionally, we learned how to write a simple SSL verification tool using Python. It’s crucial to recognize the critical role SSL certificates play in web security and remember that tools like these can be utilized to assess the security of websites.

Leave a Comment

Join our Mailing list!

Get all latest news, exclusive deals and academy updates.