【问题标题】:Working with PEM files using python for SSL connection使用 python 处理 PEM 文件进行 SSL 连接
【发布时间】:2020-03-31 17:54:19
【问题描述】:

我有 PEM 文件,其中包含 RSA 私钥和证书列表。我正在使用以下代码使用 pem 包将 PEM 文件分离为密钥文件和证书文件,然后将它们插入到烧瓶服务器中。

此代码有效,但我想看看是否有使用 python 处理 pem 文件的有效方法?

Python 代码:

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()

【问题讨论】:

    标签: python ssl python-cryptography


    【解决方案1】:

    您应该能够将您的MyPEMFile.pem 用作certfilekeyfile。底层 OpenSSL 只会从文件中提取 certfile 参数的证书和 keyfile 参数的密钥。简而言之,扔掉 PEM 解析,然后做:

    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()
    

    【讨论】:

      【解决方案2】:

      You can get your answer here. 否则使用下面的 sn-p :

      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()
      

      编码愉快!!! 你需要缩进它。 (道歉)

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-04-23
        • 2016-03-06
        • 2019-05-09
        • 2013-10-25
        • 1970-01-01
        相关资源
        最近更新 更多