如何用Python SSL与OpenSSL获取指定站点完整SSL证书链(解决SNI问题)
问题:SSL证书链检测异常,无法获取正确根证书信息
我正在研究互联网上不受信任根证书的使用要求,目前在SSL证书链检测环节遇到问题。
我原本使用以下函数检测指定证书:
def _get_root_cert(link: str): cert = ssl.get_server_certificate((link.split('//')[1], 443)) x509 = crypto.load_certificate(crypto.FILETYPE_PEM, cert.encode()) return x509.get_issuer().get_components()[2][1].decode()
该代码运行正常,但针对部分站点(如mintrans.ryazan.gov.ru),我得到的是“No-Sni证书名”而非预期的Russian Trusted CA。因此我需要获取完整的SSL证书链,但尝试的代码未达到预期效果,恳请各位提供帮助。
我用于检测证书链的实验代码如下:
import socket import ssl import base64 import binascii hostname: str = 'https://mintrans.ryazan.gov.ru' # Set up a socket connection to the site context = ssl.create_default_context() context.check_hostname = False context.verify_mode = ssl.CERT_NONE with socket.create_connection((hostname, 443)) as sock: with context.wrap_socket(sock, server_hostname=hostname) as sock: # Get the certificate chain cert_chain = sock.getpeercert(True) # cert_chain_b64 = base64.b64encode(cert_chain).decode('utf-8') # cert_chain_bytes = binascii.a2b_base64(cert_chain_b64) # cert_chain_text = cert_chain_bytes.decode('utf-8') cert_chain_text = None try: cert_chain_text = cert_chain.decode('utf-8') except UnicodeDecodeError: pass if cert_chain_text is None: try: cert_chain_text = cert_chain.decode('latin-1') except UnicodeDecodeError: pass if cert_chain_text is None: try: cert_chain_text = cert_chain.decode('windows-1252') except UnicodeDecodeError: pass if cert_chain_text is None: # Handle the error if none of the encodings work print('Unable to decode certificate chain') print(cert_chain_text)
内容的提问来源于stack exchange,提问作者sigseg5
相关产品推荐
相关产品推荐

