read certificate(.crt) and key(.key) file in python
Asked Answered
D

2

8

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?

Discredit answered 5/8, 2016 at 6:44 Comment(4)
More information please. Why are you unable to read your local certificate and key?Maurine
sure thing. Just made the changesDiscredit
I believe you are using the wrong method here. The dump_certificate method expects an X509 certificate and it dumps it to a string. You seem to want to load the certificate from a string. Have you tried using load_certificate?Maurine
Yes i have. i replaced dump with load but then i got another error OpenSSL.crypto.Error: [('asn1 encoding routines', 'ASN1_CHECK_TLEN', 'wrong tag'), ('asn1 encoding routines', 'ASN1_ITEM_EX_D2I', 'nested asn1 error'), ('asn1 encoding routines', 'ASN1_TEMPLATE_NOEXP_D2I', 'nested asn1 error'), ('PEM routines', 'PEM_ASN1_read_bio', 'ASN1 lib')]Discredit
F
4

@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>
Folia answered 13/9, 2017 at 20:48 Comment(0)
D
1

Which format in your .crt file. Are there:

  1. text starting with -----BEGIN CERTIFICATE-----
  2. base64 text started with MI chars
  3. binary data starting with \x30 byte?

In first two case there are PEM format, but in second one you are missing staring line, just add it to get correct PEM file or convert file to binary with base64 and get third case.

In third case you have DER format, so to load it you should use OpenSSL.crypto.FILETYPE_ASN1

Dorie answered 30/8, 2016 at 14:51 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.