You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Python3中获取SSL连接的完整CA证书链及元数据?

获取SSL连接完整证书链及元数据

标准库+第三方库解决方案

Python标准库ssl模块的s.getpeercert()默认仅返回服务器叶证书,而get_ca_certs()获取的是本地信任根列表,并非当前连接的完整证书链。要获取连接时的完整证书链,可通过以下步骤实现:

步骤1:安装依赖库

pip install cryptography

步骤2:修改代码解析完整证书链

import ssl
import socket
from cryptography import x509
from cryptography.hazmat.backends import default_backend

__hostname = "apple.com"
__port = 443

# 创建SSL上下文
ctx = ssl.create_default_context()

with ctx.wrap_socket(socket.socket(), server_hostname=__hostname) as s:
    s.connect((__hostname, __port))
    # 获取DER格式的完整证书链(包含叶证书+中间CA)
    cert_chain_der = s.getpeercert(binary_form=True)
    
    full_chain_info = []
    # 逐个解析证书并提取元数据
    for cert_der in cert_chain_der:
        cert = x509.load_der_x509_certificate(cert_der, default_backend())
        cert_metadata = {
            "subject": dict(cert.subject.rfc4514_attributes()),
            "issuer": dict(cert.issuer.rfc4514_attributes()),
            "notBefore": cert.not_valid_before_utc.isoformat(),
            "notAfter": cert.not_valid_after_utc.isoformat(),
            "serialNumber": str(cert.serial_number),
            "version": cert.version.value
        }
        full_chain_info.append(cert_metadata)
    
    # 输出完整证书链信息
    for index, info in enumerate(full_chain_info, start=1):
        print(f"--- 证书 {index} ---")
        print(info)

关键说明

  • getpeercert(binary_form=True)会返回当前连接中服务器发送的完整DER格式证书列表,顺序为叶证书在前,中间CA证书在后(服务器通常不会发送根CA,因为客户端本地信任库已包含)。
  • 使用cryptography库解析证书后,可直接将subject、issuer转换为字典格式,比标准库默认的嵌套列表更易读。

内容的提问来源于stack exchange,提问作者TheScriptGuy

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.15 00:31:05