获取python应用程序以访问Windows证书管理器中存储的证书

时间:2020-03-03 19:11:32

标签: python python-3.x windows ssl

我将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

1 个答案:

答案 0 :(得分:0)

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字符串,我怀疑它会起作用。