python - 让 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
解决方案
该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 字符串,我怀疑它会起作用。
推荐阅读
- c# - 实体框架 - 在子实体条件下过滤和检索子实体
- search - Google Search Console api 不允许我查询自己的域
- flutter - 如何在字符串的右上角设置星号符号?
- terraform - VS 代码中的 Terraform
- pygame - 使用 pygame.time.delay() 时在 pygame 中遇到延迟
- javascript - 在 map 函数中引用下一个元素
- reactjs - 如何将 Gatsby Image 组件转换为图形
- r - 使用整数值设置 x 轴刻度位置
- python - Django:如果与其他模型相关联,则更改模型值
- php - 购买后未返回 PayPal POST 变量