首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >跨平台列出python中的所有根CA证书

跨平台列出python中的所有根CA证书
EN

Stack Overflow用户
提问于 2020-10-20 12:21:33
回答 1查看 606关注 0票数 1

我正在寻找一种跨平台的方法来列出安装在正在运行的计算机上的所有根CA证书。

我试过使用ssl.enum_certificates("root"),但它只在Windows上被支持

从系统证书存储区检索证书。store_name可能是CA、根或MY中的一个。Windows也可以提供额外的证书存储。可用性: Windows \ Python 3.4+

EN

回答 1

Stack Overflow用户

发布于 2020-10-20 12:21:33

几乎跨平台-我已经编写了以下函数来列出在Linux和Windows中安装的根CA证书。See this for MacOS

示例:

代码语言:javascript
复制
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()

输出:

代码语言:javascript
复制
...
<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)>
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/64445060

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档