简体   繁体   English

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

[英]pyopenssl can't set x509 certificate [cert must be an X509 instance]

I'm using pyopenssl lib and I want to generate a p12 file using their crypto.PKCS12 object apis.我正在使用 pyopenssl lib,我想使用他们的 crypto.PKCS12 object api 生成一个 p12 文件。

so this certificate value is obtained from an API and saved in a file as below:所以这个证书值是从 API 获得的,并保存在一个文件中,如下所示:

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

which creates the file and when I run below command, there's a proper output and even when I verify it online, it shows all good:它创建了文件,当我在命令下运行时,有一个正确的 output ,即使我在线验证它,它也显示一切都很好:

openssl x509 -in cert.crt -text -noout openssl x509 -in cert.crt -text -noout

now the problem is when used the below to set the certificate to PKCS12 object, it gives an error:现在的问题是当使用下面将证书设置为 PKCS12 object 时,它会给出一个错误:

from OpenSSL import crypto

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

then it throws an error:然后它抛出一个错误:

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")文件“/home/someuser/.local/lib/python3.6/site-packages/OpenSSL/crypto.py”,第 2429 行,在 set_certificate raise TypeError("cert must be an X509 instance")

I can't understand why the lib is complaining about the certificate.我不明白为什么 lib 抱怨证书。 Is there anything I'm missing here?我在这里有什么遗漏吗?

It's required to load the certificate as an X509 object before setting it to a PKCS12 container.在将证书设置为PKCS12容器之前,需要将证书加载为X509 object。

So in the first place you should:所以首先你应该:

  • Read the content of the certificate file into a buffer将证书文件的内容读入缓冲区
  • Create an X509 from the buffer using load_certificate使用load_certificate从缓冲区创建 X509

As a result it may look like as follows:结果可能如下所示:

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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM