Python 使用stringIO对象作为ssl密钥/证书文件

Python 使用stringIO对象作为ssl密钥/证书文件,python,python-3.x,twisted,stringio,twisted.internet,Python,Python 3.x,Twisted,Stringio,Twisted.internet,我想从环境变量中提取ssl证书和密钥,而不是将它们存储在文件系统中。但我遇到了扭曲ssl的路障 from io import StringIO from twisted.internet import reactor, task, threads, ssl key = StringIO() key.write(os.environ['SSLKEY']) cert = StringIO() cert.write(os.environ['SSLCERT']) contextFactory = s

我想从环境变量中提取ssl证书和密钥,而不是将它们存储在文件系统中。但我遇到了扭曲ssl的路障

from io import StringIO
from twisted.internet import reactor, task, threads, ssl

key = StringIO()
key.write(os.environ['SSLKEY'])
cert = StringIO()
cert.write(os.environ['SSLCERT'])

contextFactory = ssl.DefaultOpenSSLContextFactory(key, cert)    
给我以下的例外

2018-04-03 16:01:28-0500 [-] TypeError: Path must be represented as bytes or unicode string

给我以下的例外

2018-04-03 16:02:44-0500 [-] OpenSSL.SSL.Error: [('system library', 'fopen', 'File name too long'), ('BIO routines', 'file_ctrl', 'system lib'), ('SSL routines', 'SSL_CTX_use_certificate_file', 'system lib')]
twisted.internet.ssl正在查找文件名的字符串或字节对象,io.StringIO为我提供了一个io.StringIO对象


还有什么方法可以做到这一点吗?

使用
io.BytesIO
而不是
io.StringIO

from io import BytesIO
key = BytesIO()
key.write(os.environ['SSLKEY'].encode())

Twisted使用OpenSSL实际实现TLS。Twisted仅仅提供了一个围绕OpenSSL API的包装器,以使它们更易于使用

DefaultOpenSSLContextFactory
初始值设定项接受证书和密钥文件名,而不是证书和密钥本身。因此,使用此API无法实现所需的功能

twisted.internet.ssl.CertificateOptions
将接受密钥和证书对象作为其初始值设定项:

from os import environb
from twisted.internet.ssl import (
    CertificateOptions,
    PrivateCertificate,
)

cert = PrivateCertificate.loadPEM(
    environb['SSLKEY'] + b'\n' + environb['SSLCERT'],
)
key = cert.privateKey

contextFactory = CertificateOptions(
    privateKey=key.original,
    certificate=cert.original,
)
使用
加密
库(有望在不久的将来取代大量
twisted.internet.ssl
密钥和证书管理API)加载证书可能还有更好的方法


还要注意,将私钥放入进程中的环境变量会将其暴露给同一主机上的所有其他用户和进程。这是一个非常糟糕的主意(毕竟不是很隐私)。因此,您可能应该将您的密钥放在其他地方。

我无法使其正常工作,但我将此标记为成功,因为这是一个坏主意,而我将这些机密作为文件存储在系统中。
from os import environb
from twisted.internet.ssl import (
    CertificateOptions,
    PrivateCertificate,
)

cert = PrivateCertificate.loadPEM(
    environb['SSLKEY'] + b'\n' + environb['SSLCERT'],
)
key = cert.privateKey

contextFactory = CertificateOptions(
    privateKey=key.original,
    certificate=cert.original,
)