我正在尝试了解如何使用 Python 库 Twisted 设置 SSL 链接。我已经设法创建了一个在服务器端工作的证书,但是当涉及到客户端时我完全被卡住了。
扭曲的例子website状态:
The following examples rely on the files server.pem (private key and self-signed certificate together) and public.pem (the server’s public certificate by itself).
我已经使用 OpenSSL 为自己生成了证书和 key :
# Generate Private Key:
openssl genrsa -des3 -out certs/server.key 2048
# Generate Certificate Signing Request:
openssl req -new -key certs/server.key -sha256 -out certs/server.csr
# Generate a Self-Signed Certificate:
openssl x509 -req -days 365 -in certs/server.csr -signkey certs/server.key -sha256 -out certs/server.crt
# Convert the CRT to PEM format:
openssl x509 -in certs/server.crt -out certs/server.pem -outform PEM
对于服务器端,我结合了 certs/server.crt 和 certs/server.key 来创建 server.pem 并尝试将 server.crt 用于公共(public)。
当我尝试运行我的测试程序时:
certificate = ssl.PrivateCertificate.loadPEM(certData)
我收到关于未开始行的错误。如果不是 server.crt,我应该为客户端使用哪个证书?
最佳答案
如果您还想为客户端提供基于证书的身份验证:
我前段时间遇到过这个问题并写了一个 blog post关于我的解决方案。 它还包含创建证书并使用自己的证书颁发机构对其进行签名的指南。您可以在 GitHub 找到 Python 示例代码.
它使用 Twisted 作为一个简单的 JSONRPCServer 为服务器和客户端提供基于证书的身份验证。
主要是为客户端定义一个自己的AltCtxFactory:
# Use our own context factory to use our certificate to authenticate
# against the server and ensure that we are using a strong SSL/TLS
# encryption method
class AltCtxFactory(ssl.ClientContextFactory):
def getContext(self):
# Used TLS/SSL encryption method
sslMethod = SSL.TLSv1_2_METHOD
# Clients private Key, used for authentication
privKey = "<PATH TO YOUR PRIVATE KEY>"
# Clients certificate, used for authentication
certificate = "<PATH TO YOUR CERTIFICATE>"
# Our trusted Certificate Authority for server connections
accepted_ca = "<PATH TO YOUR ACCEPTED CERTIFICATE AUTHORITY>"
self.method = sslMethod
ctx = ssl.ClientContextFactory.getContext(self)
# Ensure that we verify server's certificate and use our own
# verifyCallback method to get further details of invalid certificates
ctx.set_verify(SSL.VERIFY_PEER | SSL.VERIFY_FAIL_IF_NO_PEER_CERT,
verifyCallback)
# Ensure that we only trust our CA
ctx.load_verify_locations(accepted_ca)
# Use our own Callback mehtod if a password is needed to decrypt our
# private key
ctx.set_passwd_cb(password_cb)
# Use our certificate for authentication against server
ctx.use_certificate_file(certificate)
# Use our private key for authentication against server
ctx.use_privatekey_file(privKey)
return ctx
请随意在您的项目中使用代码。
关于python - Python Twisted SSL 的证书生成,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54288426/