I wrote a C# program that uses HttpWebRequest
to connect to an HTTPS site. The GetResponse()
method throws an exception:
Sy
The solution I ultimately implemented was to write a class implementing ICertificatePolicy with custom validation logic:
private X509CertificateCollection _certs;
private ICertificatePolicy _defaultPolicy;
public bool CheckValidationResult(ServicePoint svcPoint, X509Certificate cert, WebRequest req, int problem)
{
if ((_defaultPolicy != null) && _defaultPolicy.CheckValidationResult(svcPoint, cert, req, problem))
{
return true;
}
foreach (X509Certificate caCert in _certs)
{
if (caCert.Equals(cert))
{
return true;
}
}
return false;
}
(Error-checking omitted for brevity.)
_defaultPolicy
can be set to ServicePointManager.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 by ServerCertificateValidationCallback
, but I needed to support an old version of .NET.