6

I want to send a certificate from a "certificate authority" to a node through sockets. I have a certificate created using this example https://skippylovesmalorie.wordpress.com/2010/02/12/how-to-generate-a-self-signed-certificate-using-pyopenssl/ How would I convert this into a .pem file so I can send it as a string through a socket and then convert it on the other end back into a .pem and use get_certificate to extract this certificate from it. Python: reading a pkcs12 certificate with pyOpenSSL.crypto Its probably a hacky way to do it, but I want to simplify it for myself. (or not)

I'm resurrecting the question of this person whos question was not answered How to convert PyOpenSSL object to PEM-encoded string?

Community
  • 1
  • 1
DustBunny
  • 860
  • 2
  • 11
  • 25

1 Answers1

9

This is for generating a certificate signing request, but the concept should be the same

from OpenSSL import crypto

req = crypto.X509Req()
pkey = crypto.PKey()
pkey.generate_key(crypto.TYPE_RSA, 2048)
req.set_pubkey(pkey)
req.sign(pkey, 'sha1')
certreq = crypto.dump_certificate_request(crypto.FILETYPE_PEM, req)
certreq = certreq.replace('-----BEGIN CERTIFICATE REQUEST-----\n', '').replace('-----END CERTIFICATE REQUEST-----\n', '')
private_key = crypto.dump_privatekey(crypto.FILETYPE_PEM, pkey)

for a certificate you can use:

crypto.dump_certificate(type, cert)
turtlebender
  • 1,907
  • 15
  • 16
  • and if I just use this line root_cert = crypto.load_certificate(crypto.FILETYPE_PEM, certreq) it will convert the certificate into the format I had before? – DustBunny Mar 21 '12 at 14:07
  • Would you know a way how I can extract a public key from a certificate? There is a function for dump_privatekey which works great, but I need something similar. get_pubkey returns an object PKey which I dont know how to convert to a public key – DustBunny Mar 21 '12 at 21:12
  • Probably you solved this already. The function you want is dump_certificate – cristi Aug 24 '17 at 10:08