libcurl https示例错误

时间:2018-02-14 14:32:34

标签: c curl https ssl-certificate

我从curl网页下载并略微调整了此c example。测试应用程序使用我以前构建的curl.dll。如果不禁用对等验证,我将无法连接到https服务器。

我原来的测试应用程序:

curl_global_init(CURL_GLOBAL_DEFAULT);
CURL *curl = curl_easy_init();
if(curl) 
{
    curl_easy_setopt(curl, CURLOPT_VERBOSE, 1);
    curl_easy_setopt(curl, CURLOPT_URL, "https://example.com/");
    CURLcode res = curl_easy_perform(curl);
    if(res != CURLE_OK)
        printf ("res = %d curl_easy_perform() failed: %s\n",res, curl_easy_strerror(res));
    curl_easy_cleanup(curl);
}
curl_global_cleanup();

输出结果为:

*   Trying XX.XXX.XXX.XX...
* TCP_NODELAY set
* Connected to example.com (XX.XXX.XXX.XX) port 443 (#0)
* ALPN, offering http/1.1
* SSL certificate problem: unable to get local issuer certificate
* Closing connection 0
res = 60 curl_easy_perform() failed: Peer certificate cannot be authenticated with given CA certificates

如果我从我的exe旁边的mozilla下载并存储cacert.pem文件并将样本调整为:

curl_global_init(CURL_GLOBAL_DEFAULT);
CURL *curl = curl_easy_init();
if(curl) 
{
    curl_easy_setopt(curl, CURLOPT_VERBOSE, 1);
    curl_easy_setopt(curl, CURLOPT_URL, "https://example.com/");
    curl_easy_setopt(curl, CURLOPT_CAPATH, ".");
    CURLcode res = curl_easy_perform(curl);
    if(res != CURLE_OK)
        printf ("res = %d curl_easy_perform() failed: %s\n",res, curl_easy_strerror(res));
    curl_easy_cleanup(curl);
}
curl_global_cleanup();

我仍然收到错误消息

*   Trying XX.XXX.XXX.XX...
* TCP_NODELAY set
* Connected to example.com (XX.XXX.XXX.XX) port 443 (#0)
* ALPN, offering http/1.1
* successfully set certificate verify locations:
*   CAfile: none
      CApath: .
* SSL certificate problem: unable to get local issuer certificate
* Closing connection 0
res = 60 curl_easy_perform() failed: Peer certificate cannot be authenticated with given CA certificates

如果禁用对等验证,它工作正常。

curl_global_init(CURL_GLOBAL_DEFAULT);
CURL *curl = curl_easy_init();
if(curl) 
{
    curl_easy_setopt(curl, CURLOPT_SSL_VERIFYPEER, 0);
    curl_easy_setopt(curl, CURLOPT_VERBOSE, 1);
    curl_easy_setopt(curl, CURLOPT_URL, "https://example.com/");
    curl_easy_setopt(curl, CURLOPT_CAPATH, ".");
    CURLcode res = curl_easy_perform(curl);
    if(res != CURLE_OK)
        printf ("res = %d curl_easy_perform() failed: %s\n",res, curl_easy_strerror(res));
    curl_easy_cleanup(curl);
}
curl_global_cleanup();

有谁知道导致这种行为的原因是什么?我必须设置对等证书吗?我没有为此找到一个二传手。

1 个答案:

答案 0 :(得分:0)

我通过添加选项 CAINFO

解决了这个问题
curl_global_init(CURL_GLOBAL_DEFAULT);
CURL *curl = curl_easy_init();
if(curl)
{
    curl_easy_setopt(curl, CURLOPT_VERBOSE, 1);
    curl_easy_setopt(curl, CURLOPT_URL, "https://example.com/");
    curl_easy_setopt(curl, CURLOPT_CAINFO, "cacert.pem");
    CURLcode res = curl_easy_perform(curl);
    if(res != CURLE_OK)
        printf ("res = %d curl_easy_perform() failed: %s\n",res, curl_easy_strerror(res));
    curl_easy_cleanup(curl);
}
curl_global_cleanup();