How to add a trusted CA certificate (NOT a client certificate) to HttpWebRequest?

后端 未结 2 1419
盖世英雄少女心
盖世英雄少女心 2021-01-02 10:52

I wrote a C# program that uses HttpWebRequest to connect to an HTTPS site. The GetResponse() method throws an exception:

Sy

2条回答
  •  被撕碎了的回忆
    2021-01-02 11:26

    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.

提交回复
热议问题