让python应用程序访问存储在windows证书管理器中的证书

2024-04-25 03:43:16 发布

您现在位置:Python中文网/ 问答频道 /正文

我在windows证书管理器中存储了API.crt->;受信任的根证书颁发机构。该列表将证书的名称显示为“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

Tags: insslcertifiswindowscontextload
1条回答
网友
1楼 · 发布于 2024-04-25 03:43:16

^{}方法采用三个关键字参数:

  • cafile

    the path to a file of concatenated CA certificates in PEM format

  • capath

    the path to a directory containing several CA certificates in PEM format

  • cadata

    either an ASCII string of one or more PEM-encoded certificates or a bytes-like object of DER-encoded certificates

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

在这两个调用中,您都将参数作为位置传递,因此它被分配给第一个关键字参数(cafile)。在第一个调用中,您的参数实际上是文件的路径,因此它可以按预期工作。在第二种情况下,它不是一个文件路径,因此调用会以FileNotFoundError失败

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

相关问题 更多 >