python - pyopenssl 无法设置 x509 证书 [证书必须是 X509 实例]

标签 python python-3.x openssl x509certificate pyopenssl

我正在使用 pyopenssl lib,我想使用其 crypto.PKCS12 对象 api 生成 p12 文件。

因此该证书值是从 API 获取并保存在文件中,如下所示:

echo -e "-----cert text with begin & end-----" > cert.crt

它创建了文件,当我运行下面的命令时,有一个正确的输出,即使我在线验证它,它也显示一切正常:

openssl x509 -in cert.crt -text -noout

现在的问题是,当使用下面的方法将证书设置为 PKCS12 对象时,会出现错误:

from OpenSSL import crypto

p12 = crypto.PKCS12()
p12.set_certificate("/home/someuser/Documents/path/to/cert.crt")

然后它抛出一个错误:

File "/home/someuser/.local/lib/python3.6/site-packages/OpenSSL/crypto.py", line 2429, in set_certificate raise TypeError("cert must be an X509 instance")

我不明白为什么库会提示证书。我在这里缺少什么吗?

最佳答案

在将证书设置为 PKCS12 容器之前,需要将证书作为 X509 对象加载。

所以首先你应该:

  • 将证书文件的内容读入缓冲区
  • 使用 load_certificate 从缓冲区创建 X509

结果可能如下所示:

from OpenSSL import crypto

with open("/home/someuser/Documents/path/to/cert.crt", "r") as file:
    data = file.read()

x509 = crypto.load_certificate(crypto.FILETYPE_PEM, data);

p12 = crypto.PKCS12()
p12.set_certificate(x509)

关于python - pyopenssl 无法设置 x509 证书 [证书必须是 X509 实例],我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58688558/

相关文章:

对 NamedTuple 的 Python 类型支持

python - 如何使用 Google API 客户端创建 Python 代码

python - 如何构建我的 Python 项目以允许从子目录导入命名模块

python - 如何在 SQLAlchemy 中连接两个表中的数据?

python - 为单词python创建一个嵌套字典

c# - CF.NET SMTP - 使用 Gmail 发送电子邮件

c - 混合 openssl API 和 BSD sockets API

C++ AES OpenSSL

python - 图像分类任务的损失为 NaN

python - Pyinstaller 无法与 Panda3D 一起使用 – 未找到 'direct' 模块