Adding self-signed SSL certificate for libcurl

痴心易碎 提交于 2019-12-04 08:34:18

问题


I am using libcurl in my C application to communicate with an HTTPS server that I have set up. I generated a self-signed certificate on that server that I wish to use with curl.

I am aware of setting CURLOPT_SSL_VERIFYPEER to 0 to bypass the SSL verification, but I wish to add the generated certificate to curl's "valid" CA certificates.

I have tried setting CURLOPT_CAPATH and CURLOPT_SSLCERT to the location of the server SSL public key, but it fails to pass the verification.

How can I add my own CA/Self-signed certificate so that libcurl will successfully validate it?


回答1:


To add a self-signed certificate, use CURLOPT_CAINFO

To retrieve the SSL public certificate of a site, use

openssl s_client -connect www.site.com:443 | tee logfile

The certificate is the portion marked by ----BEGIN CERTIFICATE---- and
---END CERTIFICATE----.

Save that certificate into a file, and use curl in a manner like so:

CURL* c = curl_easy_init();
curl_easy_setopt(c, CURLOPT_URL, "https://www.site.com");
curl_easy_setopt(c, CURLOPT_CAINFO, "/path/to/the/certificate.crt");
curl_easy_setopt(c, CURLOPT_SSL_VERIFYPEER, 1);
curl_easy_perform(c);
curl_easy_cleanup(c);



回答2:


First, you kind of mix "Certificate Authority" files and "Certificate" files which confuses me.

How can I add my own CA/Self-signed certificate so that libcurl will successfully validate it?

This might be seen as a complementary answer to the one above. In the case you want to add a self-signed CA (every root-CA is self-signed) so that libcurl will successfully validate a website's certificate, which has been generated by the CA, then continue reading.

With CURLOPT_CAINFO you need to pass the "Certificate Authority" file (CA) that was used when generating the (non-CA) certificate of the site you want to verify.

(I do not know if this option works by passing it a non-CA certificate, the documentation is not really clear on this, and the previous answer has 2 up-votes, so if anyone has tested it please comment)

You can also pass a Certificate Authority chain file that contains the CA that was used, in case it was not a root-CA.

Here's a little tutorial I've found that can help you test your solution:

Creating a private root CA: http://www.flatmtn.com/article/setting-openssl-create-certificates

Creating a site certificate: http://www.flatmtn.com/article/setting-ssl-certificates-apache



来源:https://stackoverflow.com/questions/8876944/adding-self-signed-ssl-certificate-for-libcurl

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!