How to check a SSL certificate expiration date with aiohttp?

azmeuk picture azmeuk · May 31, 2017 · Viewed 24.5k times · Source

I know how to get certificate information such as expiration date using pyopenssl for instance, but is it possible to do it with a aiohttp response object?

Answer

BoboDarph picture BoboDarph · May 31, 2017

I couldn't find it in the documentation of aiohttp, but you can use ssl to get the cert and OpenSSL to get it's notAfter date and compare it to your current date in order to figure out if it's expired or not. More details here How to import OpenSSL in python And a snippet of code that does pretty much what you need below You will need to install OpenSSL beforehand however

pip install pyopenssl

import OpenSSL
import ssl, socket
cert=ssl.get_server_certificate(('www.google.com', 443))
x509 = OpenSSL.crypto.load_certificate(OpenSSL.crypto.FILETYPE_PEM, cert)
x509.get_notAfter()

For sites that make use of SNI, see the following answer on how to get the certificate ssl.get_server_certificate for sites with SNI (Server Name Indication)