0

I have PEM file containing RSA Private key and list of certificates in it. I am using below code to separate PEM file to Key file and certificate file using pem package and then plugin them into flask server.

This code works, But I want to see if there is an efficient way of working with pem file using python?

Python Code:

from api import app
from gevent.pywsgi import WSGIServer
import pem
from pem import RSAPrivateKey
from pem import Certificate
import os

Mylist = pem.parse_file(r"C:\Desktop\MyPEMFile.pem")
if os.path.exists("APIKEY.key") == False:
    for ele in Mylist:
        if isinstance(ele, RSAPrivateKey):
            f = open ("APIKEY.key","w")
            f.write(str(ele))
            f.close()

if os.path.exists("APICERTIFICATE.crt") == False:
    for ele in Mylist:
        if isinstance(ele, Certificate):
            f= open ("APICERTIFICATE.crt","a")
            f.write(str(ele))
            f.close


http_server = WSGIServer(("localhost", 443), app,keyfile='APIKEY.key', certfile='APICERTIFICATE.crt')
http_server.serve_forever()
user2961127
  • 963
  • 2
  • 17
  • 29

2 Answers2

1

You should be able to just use your MyPEMFile.pem as both certfile and keyfile. The underlying OpenSSL will just extract the certificates from the file for the certfile parameter and the key from the keyfile parameter. In short, throw away the PEM parsing and just do:

cert_and_key = "C:\Desktop\MyPEMFile.pem"
http_server = WSGIServer(("localhost", 443), app, \
    keyfile=cert_and_key, certfile=cert_and_key)
http_server.serve_forever()
Steffen Ullrich
  • 114,247
  • 10
  • 131
  • 172
0

You can get your answer here. Else use the below snippet :

certs = pem.parse_file(file_path)  # using pem module
            for pem_certificates in certs:
                strcert = str(pem_certificates)
                # using pyOpenSSL module. 
                loadCert = OpenSSL.crypto.load_certificate(OpenSSL.crypto.FILETYPE_PEM,
                                                           strcert)  # FILETYPE_ASC1
                issuer = loadCert.get_issuer()

Happy Coding!!! You need to indent it. (Apologies)