简体   繁体   中英

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.

so this certificate value is obtained from an API and saved in a file as below:

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:

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:

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")

I can't understand why the lib is complaining about the certificate. 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.

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

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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