Last active
November 14, 2021 23:21
-
-
Save davidfischer/9f8fbc993a3a2490c5f7513dd7aadf31 to your computer and use it in GitHub Desktop.
Check a server's SSL certificate expiry time
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import socket | |
import ssl | |
from cryptography import x509 | |
from cryptography.hazmat.primitives import hashes | |
hostnames = [ | |
"expired.badssl.com", | |
"untrusted-root.badssl.com", | |
"www.amazon.com", | |
] | |
port = 443 | |
for hostname in hostnames: | |
#context = ssl.create_default_context() | |
context = ssl.SSLContext(ssl.PROTOCOL_SSLv23) | |
with socket.create_connection((hostname, port)) as sock: | |
with context.wrap_socket(sock, server_hostname=hostname) as sslsock: | |
pem = ssl.DER_cert_to_PEM_cert(sslsock.getpeercert(True)) | |
cert = x509.load_pem_x509_certificate(pem.encode("utf-8")) | |
sha256_fingerprint = cert.fingerprint(hashes.SHA256()) | |
sha1_fingerprint = cert.fingerprint(hashes.SHA1()) | |
print("Hostname", hostname) | |
print("-" * 77) | |
print("Cert issuer", cert.issuer) | |
print("Cert subject", cert.subject) | |
print("Cert fingerprint", ':'.join('{:2X}'.format(b) for b in sha256_fingerprint)) | |
print("Cert fingerprint", ':'.join('{:2X}'.format(b) for b in sha1_fingerprint)) | |
print("Not Valid Before", cert.not_valid_before) | |
print("Not Valid After", cert.not_valid_after) | |
print("Extensions", cert.extensions) | |
print("\n\n") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment