如何验证.NET中HTTPS / SSL证书的有效性?

时间:2017-07-06 16:02:35

标签: c# .net ssl https

如何在.NET中验证HTTPS / SSL证书的有效性?

理想情况下,我想与网站建立HTTPS连接,然后查明是否以有效方式完成(证书未过期,主机名匹配,证书链受信任等),但内置HTTP客户端似乎忽略证书错误(我不确定是否需要物理下载网页来验证证书?)。

我尝试使用下面的代码(改编自评论中的答案),但ValidationCallback永远不会被调用:

    static void Main(string[] args)
    {
        String url = "https://www.example.com";
        HttpWebRequest request = WebRequest.CreateHttp(url);
        request.GetResponse();
        request.ServerCertificateValidationCallback += ServerCertificateValidationCallback;
        Console.WriteLine("End");
        Console.ReadKey();
    }

    private static bool ServerCertificateValidationCallback(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors)
    {
        if (sslPolicyErrors == SslPolicyErrors.None)
        {
            Console.WriteLine("Certificate OK");
            return true;
        }
        else
        {
            Console.WriteLine("Certificate ERROR");
            return false;
        }
    }

1 个答案:

答案 0 :(得分:6)

它没有被调用,因为您在之后设置了ValidationCallback 已经提出请求。

将其更改为:

HttpWebRequest request = WebRequest.CreateHttp( url );
request.ServerCertificateValidationCallback += ServerCertificateValidationCallback;
using( HttpWebResponse response = (HttpWebResponse)request.GetResponse() ) { }
Console.WriteLine("End");

......它会起作用。