如何使用python获取ssl证书信息
【代码】如何使用python获取ssl证书信息。
·
安装依赖
pip install OpenSSL
完整代码
"""
@Project :ssl证书验证
@File :get_ssl.py
@IDE :PyCharm
@Author :zhizhuo
@Date :2023/10/19 10:13
"""
import socket
import OpenSSL
import hashlib
def get_ssl_cert_info(host):
context = OpenSSL.SSL.Context(OpenSSL.SSL.SSLv23_METHOD)
conn = OpenSSL.SSL.Connection(context, socket.socket(socket.AF_INET, socket.SOCK_STREAM))
conn.connect((host, 443))
conn.do_handshake()
cert = conn.get_peer_certificate()
issuer_components = cert.get_issuer().get_components()
issuer_info = {component[0].decode("UTF-8"): component[1].decode("UTF-8") for component in issuer_components}
cert_info = {
'版本': str(cert.get_version()+1),
'序列号': str(cert.get_serial_number()),
'组织信息': str(cert.get_subject().organizationName),
'颁发机构': issuer_info,
'颁发者': str(cert.get_issuer().commonName),
'有效期从': str(cert.get_notBefore().decode()),
'过期时间': str(cert.get_notAfter().decode()),
'是否过期': str(cert.has_expired()),
'主题': str(cert.get_subject().CN),
'证书中使用的签名算法': cert.get_signature_algorithm().decode("UTF-8"),
'公钥长度':cert.get_pubkey().bits(),
'公钥': OpenSSL.crypto.dump_publickey(OpenSSL.crypto.FILETYPE_PEM, cert.get_pubkey()).decode("utf-8"),
'公钥SHA256指纹': hashlib.sha256(OpenSSL.crypto.dump_publickey(OpenSSL.crypto.FILETYPE_PEM, cert.get_pubkey())).hexdigest(),
'证书SHA256指纹': hashlib.sha256(OpenSSL.crypto.dump_certificate(OpenSSL.crypto.FILETYPE_PEM, cert)).hexdigest(),
}
return cert_info
if __name__ == "__main__":
host = 'www.baidu.com'
# host = 'devpress.csdn.net'
# host = 'www.butian.net'
cert_info = get_ssl_cert_info(host)
for key, value in cert_info.items():
if isinstance(value, dict):
print(f"{key}:")
for sub_key, sub_value in value.items():
print(f" {sub_key}: {sub_value}")
else:
print(f"{key}: {value}")
结果
版本: 3
序列号: 26585094245224241434632730821
组织信息: Beijing Baidu Netcom Science Technology Co., Ltd
颁发机构:
C: BE
O: GlobalSign nv-sa
CN: GlobalSign RSA OV SSL CA 2018
颁发者: GlobalSign RSA OV SSL CA 2018
有效期从: 20230706015106Z
过期时间: 20240806015105Z
是否过期: False
主题: baidu.com
证书中使用的签名算法: sha256WithRSAEncryption
公钥长度: 2048
公钥: -----BEGIN PUBLIC KEY-----
MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAuwS7hHZYB7RaiFTgala8
5dSNPh65KODXAY84K0GyWX3wrCe0JiQUOP5M6jtJUffpW0D3P6bI2g8CbiWLR5G4
Lp4AIRkdGAD83gT9Jnk5XfKQvICdqHyykYmJ2EAv5dKn815tSCvFHwqx4I6Mdv+8
0WcK0knWCe4mAwLzzM3qitUxqC2PA/1e/OQ6xolnmUzOmG36hA0OU4vmY1LFm0qp
q6MiNZkN7hn/my31pHfy7BCA9KuCudF+Nh8On5sZoPXDV92Iu87hkJw/S7rdOqlB
s92GTcLCt+j/NxPABIlDRDgR5qOW9wkiIS8sTg5+5dhcuwBEW6/e5LOw8Dy2OEVJ
XQIDAQAB
-----END PUBLIC KEY-----
公钥SHA256指纹: 4bdcfbfcf1b5948eb71e99df9157fc8f8e8579727557f1d276738feada90c8ae
证书SHA256指纹: 0eda4c1d2cfe3518cafa61a26ee3a27a7c1c7fcc04941a51991c5cc7611dfc0b
更多推荐
已为社区贡献1条内容
所有评论(0)