问题描述
我正在寻找一种跨平台的方式来列出正在运行的计算机上安装的所有Root CA证书。
我尝试使用ssl.enum_certificates("root")
,但仅Windows才支持
从Windows的系统证书库中检索证书。 store_name可以是CA,ROOT或MY之一。 Windows也可能提供其他证书存储。 可用性:Windows | Python 3.4 +
解决方法
几乎跨平台-我编写了以下函数来列出Linux和Windows中已安装的根CA证书。 See this for MacOS
示例:
import os
import ssl
from cryptography.hazmat.backends import default_backend
from cryptography import x509
import platform
def get_root_ca_certs(linux_certs_dir_path='/etc/ssl/certs'):
system = platform.system().lower()
backend = default_backend()
if system == 'windows':
items = ssl.enum_certificates("root")
for cert_bytes,encoding,is_trusted in items:
if encoding == "x509_asn":
cert = x509.load_der_x509_certificate(cert_bytes,backend)
yield cert
elif system == 'linux':
certs_file_names = os.listdir(linux_certs_dir_path)
backend = default_backend()
for cert_file_name in certs_file_names:
cert_file_path = os.path.join(linux_certs_dir_path,cert_file_name)
if not os.path.isfile(cert_file_path):
continue
with open(cert_file_path,'rb') as f:
cert_pem = f.read()
cert = x509.load_pem_x509_certificate(cert_pem,backend)
yield cert
else:
raise NotImplemented(f'missing implementation for this operating system="{system}"')
def main():
root_ca_certs = get_root_ca_certs()
root_ca_certs = list(root_ca_certs) # you can load it into a list if you are planning multiple iterations
for root_ca_cert in root_ca_certs:
print(root_ca_cert.subject)
if __name__ == '__main__':
main()
输出:
...
<Name(C=PL,O=Unizeto Sp. z o.o.,CN=Certum CA)>
<Name(C=US,ST=Washington,L=Redmond,O=Microsoft Corporation,CN=Microsoft ECC TS Root Certificate Authority 2018)>
<Name(C=US,ST=Arizona,L=Scottsdale,O=GoDaddy.com\,Inc.,CN=Go Daddy Root Certificate Authority - G2)>
<Name(C=RO,O=certSIGN,OU=certSIGN ROOT CA)>
<Name(C=US,O=DigiCert Inc,OU=www.digicert.com,CN=DigiCert High Assurance EV Root CA)>
<Name(OU=Copyright (c) 1997 Microsoft Corp.,OU=Microsoft Corporation,CN=Microsoft Root Authority)>