Python Tutorials - Herong's Tutorial Examples - v2.21, by Herong Yang
Dumping Server Certificate
This section provides a tutorial example on dumping the server certificate in DER binary or PEM text format.
If you want to dump the server certificate, you can call the sock.getpeercert(binary_form=True) method as shown in this Python example script:
#- http-client-server-certificate.py
#- Copyright (c) 2025 HerongYang.com. All Rights Reserved.
import sys
host = sys.argv[1]
cert = sys.argv[2]
import ssl
context = ssl.create_default_context()
context.load_verify_locations(cafile=cert)
import http.client
conn = http.client.HTTPSConnection(host, context=context)
conn.request("GET", "/")
sock = conn.sock
# retrieve the server certificate in DER binary format
server_cert = sock.getpeercert(binary_form=True)
# convert certificate from DER binary to PEM text format
print(ssl.DER_cert_to_PEM_cert(server_cert))
conn.close()
You can run the script and save the server certificate to a file:
herong$ python3 http-client-server-certificate.py \
www.google.com /private/etc/ssl/cert.pem > server-cert.pem
herong$ cat server-cert.pem
-----BEGIN CERTIFICATE-----
MIIEVjCCAz6gAwIBAgIQYHdrWMx4yeQSThbn1MX7njANBgkqhkiG9w0BAQsFADA7
MQswCQYDVQQGEwJVUzEeMBwGA1UEChMVR29vZ2xlIFRydXN0IFNlcnZpY2VzMQww
CgYDVQQDEwNXUjIwHhcNMjYwNDA4MDUyMDI4WhcNMjYwNzAxMDUyMDI3WjAZMRcw
...
herong$ openssl x509 -in server-cert.pem -text -noout
Certificate:
Data:
Version: 3 (0x2)
Serial Number:
60:77:6b:58:cc:78:c9:e4:12:4e:16:e7:d4:c5:fb:9e
Signature Algorithm: sha256WithRSAEncryption
Issuer: C=US, O=Google Trust Services, CN=WR2
Validity
Not Before: Apr 8 05:20:28 2026 GMT
Not After : Jul 1 05:20:27 2026 GMT
Subject: CN=www.google.com
...
Another quick way to dump the server certificate is to call the ssl.get_server_certificate((host, port)) method without making any HTTPS connection:
herong$ python3
Python 3.8.0 (v3.8.0:fa919fdf25, Oct 14 2019, 10:23:27)
>>> import ssl
>>> cert = ssl.get_server_certificate(('www.google.com', 443))
>>> print(cert)
-----BEGIN CERTIFICATE-----
MIIDfDCCAmSgAwIBAgIJAJB2iRjpM5OgMA0GCSqGSIb3DQEBCwUAME4xMTAvBgNV
BAsMKE5vIFNOSSBwcm92aWRlZDsgcGxlYXNlIGZpeCB5b3VyIGNsaWVudC4xGTAX
BgNVBAMTEGludmFsaWQyLmludmFsaWQwHhcNMTUwMTAxMDAwMDAwWhcNMzAwMTAx
...
-----END CERTIFICATE-----
Table of Contents
Variables, Operations and Expressions
Function Statement and Function Call
List, Set and Dictionary Comprehensions
Packages and Package Directories
"pathlib" - Object-Oriented Filesystem Paths
"pip" - Package Installer for Python
SciPy.org - Python Libraries for Science
pandas - Data Analysis and Manipulation
►Communicating with HTTPS Servers
http.client for HTTPS Connection
Retrieving SSLSocket Information
Use pyOpenSSL for HTTPS Connection
Generating EC Public-Private Keys
Anaconda - Python Environment Manager