在 C++ 中使用 LibCurl 和自签名证书

use*_*007 3 c++ libcurl

我在使用 libcurl 和 ssl 时遇到问题。

如果我尝试使用以下curl命令连接到我的站点:

curl -q --cert client-2048.crt --key client-2048.key https://***** -d“用户名= &密码= ”-H“X-应用程序:curlCommandLineTest”

一切正常(顺便说一下,证书是自签名的)

我怎样才能用 libcurl 做同样的事情?

我尝试遵循 libcurl ssl 示例,但证书和私钥具有不同的扩展名,因此我不知道从哪里开始。

到目前为止,我尝试了以下(以及许多其他组合):

static const char *pCertFile = "client-2048.crt";
static const char *pCACertFile = "client-2048.pem";
static const char *pKeyName = "client-2048.key";

curl_global_init(CURL_GLOBAL_DEFAULT);

curl = curl_easy_init();
if (curl) {
    /* what call to write: */
    curl_easy_setopt(curl, CURLOPT_URL, "https://*****");
    curl_easy_setopt(curl, CURLOPT_HEADERDATA, headerfile);

        /* cert is stored PEM coded in file... */
        /* since PEM is default, we needn't set it for PEM */
        curl_easy_setopt(curl, CURLOPT_SSLCERTTYPE, "PEM");

        /* set the cert for client authentication */
        curl_easy_setopt(curl, CURLOPT_SSLCERT, pCertFile);

        /* set the private key (file or ID in engine) */
        curl_easy_setopt(curl, CURLOPT_SSLKEY, pKeyName);

        /* disconnect if we can't validate server's cert */
        curl_easy_setopt(curl, CURLOPT_SSL_VERIFYPEER, 1L);

        /* Perform the request, res will get the return code */
        res = curl_easy_perform(curl);
        /* Check for errors */
        if (res != CURLE_OK)
            fprintf(stderr, "curl_easy_perform() failed: %s\n",
                curl_easy_strerror(res));

        /* we are done... */
    } while (0);
    /* always cleanup */
    curl_easy_cleanup(curl);
    return 0;
Run Code Online (Sandbox Code Playgroud)

但我收到消息:

curl_easy_perform() failed: Peer certificate cannot be authenticated with 
given CA certificates
Run Code Online (Sandbox Code Playgroud)

那么,镜像成功的调用的 Libcurl 代码会是什么呢?

谢谢

use*_*007 5

自签名证书:

curl_easy_setopt(curl, CURLOPT_SSL_VERIFYPEER, 0L);

  • 警告,此解决方案会关闭证书验证。要自己进行验证,您需要安装一个上下文函数:curl_easy_setopt (curl, CURLOPT_SSL_CTX_FUNCTION, setupPeerVerifyCallback); 并在该函数中安装验证回调。SSL_CTX_set_verify ( psslctx, SSL_VERIFY_PEER, verifyPeerCallback ); (3认同)