Python Twisted SSL 的证书生成

Certificate Generation for Python Twisted SSL

我正在尝试弄清楚如何使用 Python 库 Twisted 设置 SSL link。我已经设法创建了一个在服务器端工作的证书,但是当涉及到客户端时我完全卡住了。

来自扭曲 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 为自己生成了证书和密钥:

# 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,我应该为客户端使用哪个证书?

When I try and run my test program using:

certificate = ssl.PrivateCertificate.loadPEM(certData) I get an error about not starting line. Which certificate should I be using for the client if it's not server.crt please?

如果您查看 Twisted howto page.

上的示例,这应该是 ssl.Certificate.LoadPEM(certData)

如果您也想为客户端提供基于证书的身份验证:

我前段时间遇到过这个问题,并写了一个 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

欢迎在您的项目中使用代码。