read certificate(.crt) and key(.key) file in python

Ashish Padakannaya picture Ashish Padakannaya · Aug 5, 2016 · Viewed 11.1k times · Source

So i'm using the JIRA-Python module to connect to my company's instance on JIRA and it requires me to pass the certificate and key for this. However using the OpenSSL module,i'm unable to read my local certificate and key to pass it along the request.

the code for reading is below

import OpenSSL.crypto 
c = open('/Users/mpadakan/.certs/mpadakan-blr-mpsot-20160704.crt').read()
cert = OpenSSL.crypto.dump_certificate(OpenSSL.crypto.FILETYPE_PEM, c)

the error i get is

Traceback (most recent call last):
File "flaskApp.py", line 19, in <module>
cert = OpenSSL.crypto.dump_certificate(OpenSSL.crypto.FILETYPE_PEM, c)
TypeError: must be X509, not str

could someone tell me how to read my local .crt and .key file into x509 objects?

Answer

bear454 picture bear454 · Sep 13, 2017

@can-ibanoglu was right on:

import OpenSSL.crypto 
cert = OpenSSL.crypto.load_certificate(
    OpenSSL.crypto.FILETYPE_PEM, 
    open('/tmp/server.crt').read()
)

>>> cert
<OpenSSL.crypto.X509 object at 0x7f79906a6f50>