How to verify the validity of a website’s SSL certificate

Digital certificates are electronic credentials that serve to establish the authenticity of a person, device, or website on the internet. They play a crucial role in ensuring the security and trustworthiness of online communications and transactions.

An SSL(Secure Sockets Layer) certificate is a type of digital certificate that is specifically used to secure the communication between a web browser (or other client) and a web server. SSL is a protocolSet of rules that ensure communication between computers on a network. for encrypting data transmitted over the internet. This encryption ensures the confidentialityNo third party can read the shared data between two users. and integrityData is protected from unauthorized changes during transmission. of data exchanged over the internet. SSL certificates ensure that sensitive data transmitted between the client and the server remains private and protected from unauthorized access.

The significance of SSL certificates is given below.

  • Encryption: SSL certificates enable encryption of data transferred between a user’s browser and a web server. This encryption ensures that even if the data is intercepted by malicious actors, it cannot be easily decrypted.

  • Authentication: SSL certificates also provide a level of authentication. They verify the identity of the website’s owner, ensuring that users connect to the intended website and not a fraudulent one. This is particularly important for protecting against phishing attacks.

  • Trustworthiness: These certificates are issued by reputable Certificate Authorities (CAs) that browsers trust implicitly. When a website’s SSL certificate is signed by one of these authorities, it signals trustworthiness to the users.

  • Search Engine Optimization (SEO): SSL-certified websites often enjoy higher search engine rankings. Leading search engines prioritize secure connections as a ranking factor. Hence, SSL certificates indirectly contribute to improved online visibility and user traffic.

SSL certificate fields

When an SSL certificate is installed on a web server, the website’s URL changes from http:// to https://. The s in https stands for secure, indicating that the site uses SSL encryption. The SSL certificate contains several fields which obtain crucial information. The SSL certificate fields are as follows:

  • Version: The version of the SSL certificate.

  • Serial number: A unique identifier for the certificate.

  • Signature algorithm: The algorithm used to sign the certificate.

  • Issuer: The name of the Certificate Authority (CA) that issued the certificate.

  • Validity period: The certificate’s start and expiration dates.

  • Subject: Details about the entity or website to which the certificate was issued.

    • Common Name (CN): The fully qualified domain name (FQDN) of the website.

    • Organization (O): The organization’s name (if included).

    • Organizational Unit (OU): The organizational unit (if included).

    • Locality (L): The locality (if included).

    • State (ST): The state or province (if included).

    • Country (C): The country (if included).

  • Subject Public Key Info:

    • Public Key: The public key used for encryption.

    • Public Key Algorithm: The encryption algorithm used with the public key.

  • Extensions: Additional information and settings about the certificate. Some of them include.

    • Certificate Key Usage: It specifies how the public key in an SSL certificate can be used.

    • Extended Key Usage: It indicates specific purposes for which the certificate is valid, like server authentication, client authentication, or code signing digitally signing software code with a cryptographic signature.

    • Certificate Subject Alternative Name: An SSL certificate extension that allows multiple domain names or identifiers to be covered by a single certificate.

    • Certificate Policies: It details the issuer’s practices and policies regarding certificate issuance and usage.

  • Certificate Signature Algorithm: The cryptographic algorithm used to create the digital signature on the SSL certificate.

  • Certificate Signature Value: The actual digital signature generated by applying the private key to the certificate’s contents.

  • Fingerprints: Unique cryptographic hash values, like SHA-1 or SHA-256, are used for verifying the integrity of the certificate.

By examining the SSL certificate’s fields, including its expiration date, issuer’s identity, and cryptographic details, we enhance data privacy and build trust in online interactions, resulting in a secure and smooth user experience. Conversely, expired or invalid certificates may expose data to potential security risks. Therefore, the verification of SSL certificate validity stands as an essential procedure to guarantee a secure and dependable connection to a website.

Code

import ssl
import socket
import datetime
from urllib.parse import urlparse
def check_ssl_certificate(url):
try:
# Extract the domain from the URL
parsed_url = urlparse(url)
domain = parsed_url.netloc
# Create an SSL context and connect to the server
ctx = ssl.create_default_context()
with ctx.wrap_socket(socket.socket(), server_hostname=domain) as ssock:
ssock.connect((domain, 443))
cert = ssock.getpeercert()
# Extract certificate expiration date and get current date
expiration_date = datetime.datetime.strptime(cert['notAfter'], '%b %d %H:%M:%S %Y %Z')
current_date = datetime.datetime.now()
# Check if the certificate has expired
if expiration_date < current_date:
return f"The SSL certificate for {domain} has expired on {expiration_date}."
else:
return f"The SSL certificate for {domain} is valid until {expiration_date}."
except Exception as e:
return f"An error occurred: {str(e)}"
url = 'https://www.educative.io' #input("Enter the complete URL (e.g., https://www.example.com): ")
result = check_ssl_certificate(url)
print(result)
  • Line 1: It imports the ssl module to provide access to Secure Socket Layer (SSL) and Transport Layer Security (TLS) protocols.

  • Line 2: It imports the socket module, which allows for network socket operations to establish connections to the websites.

  • Line 3: It imports the datetime module to work with dates and times.

  • Line 4: It imports the urlparse function for parsing URLs.

  • Lines 67: We define a function check_ssl_certificate(url) and use a try/exception block for unexpected errors.

  • Line 9: The urlparse function breaks down the URL into its components, such as domain or IP address, path, query parameters, and more.

  • Line 10: It extracts the domain name or IP address from the parsed URL and assigns it to the variable domain.

  • Line 13: It creates SSL context ctx. It is an SSL configuration that defines various security parameters and options for SSL/TLS connections.

  • Line 14: It sets up a secure socket connection and creates a standard network socket. The socket is wrapped with SSL/TLS encryption. We specify the hostname of the server to which the connection is being established for SSL handshake and certificate validation.

  • Lines 1516: It establishes a connection to the remote server domain on port 443. Once the connection is established, the getpeercert() function retrieves the SSL certificate presented by the remote server. The certificate is in the form of a Python dictionary, which includes various certificate details.

  • Line 19: It parses the expiration date of the SSL certificate cert['notAfter'] and converts it into a datetime object.

  • Line 20: It stores the current date and time in the current_date variable.

  • Lines 2326: We compare the SSL certificate’s expiration date with the current date and time. If the certificate has expired, the code returns a message indicating the expiration date; otherwise, it confirms the certificate’s validity until the specified expiration date for the given domain.

  • Lines 2829: It handles any potential errors that can arise during the SSL certificate validation process.

  • Lines 3133: We initialize a variable url with the value https://www.educative.io and call a function check_ssl_certificate to validate the SSL certificate for the provided url and store the result in the variable result. Finally, we print the result.

Free Resources

Copyright ©2025 Educative, Inc. All rights reserved