使用 python 的带有自签名证书的 ssl

ssl with self signed certificate using python

我正在尝试使用我的自签名证书在 python 中构建一个简单的服务器。 我使用 makecert 创建了 .cer、.pfx、.pvk 文件。

context = ssl.create_default_context(ssl.Purpose.CLIENT_AUTH)
context.load_cert_chain(certfile="ServerSSL.cer")

Traceback (most recent call last):
  File "ssl_server.py", line 4, in <module>
    context.load_cert_chain(certfile="ServerSSL.cer")
ssl.SSLError: [SSL] PEM lib (_ssl.c:2580)

我做错了什么? 我也尝试通过更改后缀将我的cer文件转换为pem,但我得到了同样的错误。

当您查看 _ssl.c:2580 的原始来源时,您会发现 SSL_CTX_use_certificate_chain_file 失败了。由于 pw_info.errorerrno 均未设置,因此查找原因并不容易。问题可能是由 crt 文件引起的。在文本编辑器中打开它并检查文件看起来是否与它应该看起来的完全一样 - 还要验证换行符。如果它们不完全匹配,函数调用将失败。

2567:    PySSL_BEGIN_ALLOW_THREADS_S(pw_info.thread_state);
2568:    r = SSL_CTX_use_certificate_chain_file(self->ctx, certfile_bytes);
2569:    PySSL_END_ALLOW_THREADS_S(pw_info.thread_state);
2570:    if (r != 1) {
2571:        if (pw_info.error) {
2572:            ERR_clear_error();
2573:            /* the password callback has already set the error information */
2574:        }
2575:        else if (errno != 0) {
2576:            ERR_clear_error();
2577:            PyErr_SetFromErrno(PyExc_IOError);
2578:        }
2579:        else {
2580:            _setSSLError(NULL, 0, __FILE__, __LINE__);
2581:        }
2582:        goto error;

documentation 还说:

The certificates must be in PEM format and must be sorted starting with the subject's certificate (actual client or server certificate), followed by intermediate CA certificates if applicable, and ending at the highest level (root) CA.