2
votes

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?

1

1 Answers

0
votes

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)