我正在寻找 C++ 中的客户端 TLS 连接示例。最适合 Visual Studio,但老实说它可以是任何编译器。我找到了几个C样本。但没有人工作。我从 C 中的这个示例开始: https://wiki.openssl.org/index.php/SSL/TLS_Client
但是失败了
res = BIO_do_connect(web);
如果我想连接到我自己的node.js服务器(使用直接IP地址),则使用“系统库”,或者使用encrypted.google.com作为url使用“错误主机名查找”。 均使用 libressl 和 Visual Studio 2013。
下一站:http://fm4dd.com/openssl/sslconnect.htm
到这里程序就运行成功了。但任何在末尾写入 SSL 连接的尝试:
std::string json = "{'test':'huhu'}";
char buff[1024];
sprintf(buff, "POST /test.de HTTP/1.1 \nHost: test.de\nContent-Type: application/json\nContent-Length: %d\n\n", json.length());
std::string post = buff;
int snd = SSL_write(ssl, post.data(), post.length());
snd = SSL_write(ssl, json.data(), json.length());
强制服务器关闭连接(我不知道到底发生了什么,因为我现在不知道如何告诉 node.js 告诉我更多信息)。
所以我搜索一个工作示例或如何使用在 C++ 中运行的自己的证书获得 TLS 连接
最佳答案
I am searching for a client TLS connection example in C++.
我认为 OpenSSL 有几个到 C++ 的端口。他们尝试做完整的类包装工作。请参阅openssl++ class在 Google 上。
当我在 C++ 中使用它时,我使用唯一的指针进行清理。例如,参见 How to properly print RSA* as string in C++? 。我用它主要是为了确保清理。我认为它类似于 Resource Acquisition Is Initialization模式。
OpenSSL 还提供了类似库和框架的页面。请参阅Related Links OpenSSL wiki 上的页面。
But it fails on
res = BIO_do_connect(web);
with "system library" if I want to connect to my own node.js server (using the > direct ip address) or with "bad hostname lookup"
我的猜测是证书中的名称与要连接的 URL 中使用的名称不匹配。
您可以通过在 host
文件中添加条目来使名称发挥作用。实际上,这是您的本地 DNS 覆盖。请参阅Microsoft TCP/IP Host Name Resolution Order .
或者,您可以生成包含所有必需名称的证书。为此,请参阅How to create a self-signed certificate with openssl?
forces the server to close the connection (I do not see exactly what happend as I do not now how I can tell node.js to tell me more).
"POST /test.de HTTP/1.1 \nHost: test.de\nContent-Type: application/json\nContent-Length: %d\n\n"
由于您缺少 Connection: close
请求 header ,服务器可能会遵循 RFC 7230, HTTP/1.1 Message Syntax and Routing, Section 6.1 :
A server that does not support persistent connections MUST send the "close" connection option in every response message that does not have a 1xx (Informational) status code.
此外,这可能应该是:
"POST /test.de HTTP/1.1\r\nHost: test.de\r\nContent-Type: application/json\r\nContent-Length:%d\r\n\r\n"
\r\n
用作换行符,而不是 \r
和 \n
。双\r\n
用于终止 header 。您可以快速验证是否在标准中搜索“CRLF”。您将讨论 ABNF 语法。
So I search for a working sample or how to get a TLS connection with own certificate running in C++
这里的技巧是创建一个格式良好的证书。为此,请参阅How to create a self-signed certificate with openssl?
关于c++ - 用于客户端 TLS 连接的 OpenSSL 或 LibreSSL C++ 示例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29987200/