Function Name
cert_time_to_seconds
Function Signature
cert_time_to_seconds(cert_time)
Parameters
cert_time – The time string in "%b %d %H:%M:%S %Y %Z" strptime format.
Return Value
The number of seconds elapsed since Epoch corresponding the time specified in the parameter cert_time.
Overview
- When two hosts communicate through network I/O via stream based sockets, a host can authenticate the identity of the other host involved in the communication through the digital certificate of the other host.
- A Certificate Authority issues a digital certificate.
- Digital certificates issued by a Certificate Authority have validity for a specific time period.
- Validity of a digital certificate starts after the time specified by the field “notBefore” and ends after the elapse of the time specified by the field “notAfter”.
- The method ssl.cert_time_to_seconds(cert_time) converts the string format of the time given in the “notBefore” and “notAfter" fields to number of seconds since Epoch. The time returned is in GMT - Greenwich Mean Time.
Example
import socket
import ssl
import platform
import os
# Create an SSL context
securityContext = ssl.SSLContext();
securityContext.verify_mode = ssl.CERT_REQUIRED;
securityContext.check_hostname = True;
securityContext.load_default_certs();
# Check for OS X platform
if platform.system().lower() == 'darwin':
import certifi
securityContext.load_verify_locations(
cafile=os.path.relpath(certifi.where()),
capath=None,
cadata=None);
# Socket properties
socket_address_family = socket.AF_INET;
socket_type = socket.SOCK_STREAM;
# Create a streaming socket
connection = socket.socket(socket_address_family, socket_type);
# Create a secure socket
secure_connection = securityContext.wrap_socket(connection,
server_hostname="example.org");
# Connect to host
secure_connection.connect(("example.org",443));
# Get the certificate from the host
cert = secure_connection.getpeercert(binary_form=False);
# Get the validity related attributes
print("Certificate validity:");
print("Not before:%s"%cert['notBefore']);
# Convert the time string into timestamp
print("As timestamp:%d"%ssl.cert_time_to_seconds(cert['notBefore']));
print("Not after:%s"%cert['notAfter']);
# Convert the time string into timestamp
print("As timestamp:%d"%ssl.cert_time_to_seconds(cert['notAfter']));Output
Certificate validity:
Not before:Nov 28 00:00:00 2018 GMT
As timestamp:1543363200
Not after:Dec 2 12:00:00 2020 GMT
As timestamp:1606910400