我正在寻找一种跨平台的方式来列出运行计算机上安装的所有 Root CA 证书。
我试过使用ssl.enum_certificates("root")
,但它只在 Windows 上受支持
从 Windows 的系统证书存储中检索证书。store_name 可以是 CA、ROOT 或 MY 之一。Windows 也可能提供额外的证书存储。可用性:Windows | Python 3.4+
我正在寻找一种跨平台的方式来列出运行计算机上安装的所有 Root CA 证书。
我试过使用ssl.enum_certificates("root")
,但它只在 Windows 上受支持
从 Windows 的系统证书存储中检索证书。store_name 可以是 CA、ROOT 或 MY 之一。Windows 也可能提供额外的证书存储。可用性:Windows | Python 3.4+
几乎跨平台 - 我编写了以下函数来列出 Linux 和 Windows 中已安装的根 CA 证书。对于 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)>