PyOpenSSL reading certificate/pkey file

user2013697 picture user2013697 · Jan 28, 2013 · Viewed 18.1k times · Source

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

Answer

V13 picture V13 · Jun 18, 2013

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.