8

That's how i create certificate

  from OpenSSL import crypto

  cert = crypto.X509()
  cert.get_subject().C            = countryName
  cert.get_subject().ST           = stateOrProvinceName
  ...


Here what generation looks like.
Now, how do I extract those values fomr certificate using PyOpenSSL backwards from plain files?

So here's what I cameup with

def certext(certstr):
  p1 = Popen(['printf', certstr], stdout=PIPE)
  p2 = Popen(['openssl', 'x509', '-text'], stdin=p1.stdout, stdout=PIPE)
  p1.stdout.close()
  output = p2.communicate()[0]
  return output
user2013697
  • 157
  • 1
  • 2
  • 8

1 Answers1

19

You can load a PEM certificate as follows:

import OpenSSL.crypto

st_cert=open(certfile, 'rt').read()

c=OpenSSL.crypto
cert=c.load_certificate(c.FILETYPE_PEM, st_cert)

and a private key with:

st_key=open(keyfile, 'rt').read()
key=c.load_privatekey(c.FILETYPE_PEM, st_key)

where certfile and keyfile are the filenames.

V13
  • 853
  • 8
  • 14
  • 1
    Just wanted to also add...you don't need separate files for the cert and the private key file. They can both be in the same file and read once. When loading the private key and certificate from that one file, `OpenSSL` takes care of everything. Much more convenient. – KVISH Dec 07 '13 at 23:40