首页 > 解决方案 > 让 python 应用程序访问存储在 Windows 证书管理器中的证书

问题描述

我将 API.crt 存储在 Windows 证书管理器 -> 受信任的根证书颁发机构中。该列表将证书名称显示为“localhost”

当我在下面运行代码时,当我在函数中提供证书的路径时它会load_verify_locations()起作用。

但是当我从 Windows 证书管理器检索证书并提供实际证书时它不起作用。请任何人都可以帮助我解决这个问题。

import wincertstore
import ssl
for storename in ("CA", "ROOT"):
    with wincertstore.CertSystemStore(storename) as store:
        for cert in store.itercerts(usage=wincertstore.SERVER_AUTH):
            if cert.get_name() == 'localhost': #name of cert
                mycert = cert.get_pem()


context = ssl.SSLContext(ssl.PROTOCOL_TLSv1_2)
context.verify_mode = ssl.CERT_REQUIRED
context.load_verify_locations("C:/API.crt") ##Works if certificate is stored locally
context.load_verify_locations(mycert) ## Does not Works if certificate is passed.

Traceback (most recent call last):
  File "test.py", line 14, in <module>
    context.load_verify_locations(mycert) ## Does not Works if certificate is passed.
FileNotFoundError: [Errno 2] No such file or directory

标签: pythonpython-3.xwindowsssl

解决方案


SSLContext.load_verify_locations()方法采用三个关键字参数:

  • cafile

    PEM 格式的级联 CA 证书文件的路径

  • capath

    包含多个 PEM 格式的 CA 证书的目录的路径

  • cadata

    一个或多个 PEM 编码证书的ASCII 字符串或DER 编码证书的类似字节的对象

由于mycert = cert.get_pem(),mycert是该证书的ASCII PEM 字符串,而不是证书的路径

在这两个调用中,您将参数作为位置传递,因此它被分配给第一个关键字参数 ( cafile)。在第一次调用中,您的参数确实是文件的路径,因此它按预期工作。其次,它不是文件路径,因此调用失败并显示FileNotFoundError.

如果您将第二次调用更改context.load_verify_locations(cdata=mycert)为指定您的参数是 PEM 字符串,我怀疑它会起作用。


推荐阅读