I wrote a C# program that uses HttpWebRequest
to connect to an HTTPS site. The GetResponse()
method throws an exception:
SystemError: The underlying connection was closed: Could not establish trust relationship for the SSL/TLS secure channel.
I'm able to connect to the same website using curl.exe --cacert CAFile.pem
. I'd like to be able use the same trusted CA certificates from the C# program.
How can I get HttpWebRequest
to use this CA certificate file (or an X509CertificateCollection
containing certificates parsed from it)?
The solution I ultimately implemented was to write a class implementing ICertificatePolicy with custom validation logic:
(Error-checking omitted for brevity.)
_defaultPolicy
can be set toServicePointManager.CertificatePolicy
to allow the default certificate store to be used in addition to custom certificates._certs
contains the extra certificate(s). It's generated by parsing the PEM file and calling_certs.Add(new X509Certificate(Convert.FromBase64String(base64cert)));
CertificatePolicy
has been obsoleted byServerCertificateValidationCallback
, but I needed to support an old version of .NET.Try setting your ServerCertificateValidationCallback to use this:
I have not had an opportunity to test this, so let me know if you encounter any errors and I'll modify the answer if needed.