如何在C#中验证Web服务器证书?

时间:2016-05-24 17:08:41

标签: c# web certificate

我有一个有趣的问题。我们的团队在AWS中管理大量的Load Balancers和Web服务器。证书管理会破坏块,因此我尝试向trycorder添加一个模块,该模块将命中每个受SSL保护的端点并检查证书过期日期,以及可能有用的任何其他证书详细信息。   基于以下内容找到了一个示例,但它失败了,无法建立信任。我不在乎信任,我只需要查看正在使用的证书。

Based on help recieved, I have gotten this far, but failing because I dont understand how to recover the data from the delegate within the context of the calling function.  I need the function to return the certificate.  Can this be done? (email code if it is too large to megastiv@stiv.com. Thanks for your help!!!!

    public X509Certificate2 GetCertificate(string urltocheck)
    {
        X509Certificate2 ToReturn = new X509Certificate2();
        try
        {
            WebRequest request = WebRequest.Create(new Uri(urltocheck));
            var gimme = ServicePointManager.ServerCertificateValidationCallback =
            (object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors) =>
            {
                ToReturn = new X509Certificate2(certificate);
                return true;
            };

            ServicePoint svcPoint = ServicePointManager.FindServicePoint(new Uri(urltocheck));
            return ToReturn;
        }
        catch (Exception ex) { }
        return ToReturn;
    }

帮助?

1 个答案:

答案 0 :(得分:0)

您可以使用ServicePointManager允许任何证书,并且您有机会使用certificate参数进行检查:

 ServicePointManager.ServerCertificateValidationCallback =
                (object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors) =>
                {
                        //do stuff with certificate...
                        return true;
                };

听起来你有一个有效的用例,当然你几乎不想盲目信任任何证书。