加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

如何在c#中获取远程服务器的SSL证书信息

发布时间:2020-12-15 08:30:28 所属栏目:百科 来源:网络整理
导读:我必须在c#中开发一个应用程序,以获取基于我提供的DNS(例如* .google.com)发布的SSL证书信息,如有效期,以便如果到期日期临近,我可以主动处理它.如果我将DNS提供为* .google.com,那么我需要获取该域的SSL证书信息的详细信息. 我试过跟随http://awesomeideas.n
我必须在c#中开发一个应用程序,以获取基于我提供的DNS(例如* .google.com)发布的SSL证书信息,如有效期,以便如果到期日期临近,我可以主动处理它.如果我将DNS提供为* .google.com,那么我需要获取该域的SSL证书信息的详细信息.

我试过跟随http://awesomeideas.net/page/Cert-Expiry-Check.aspx,但我觉得它是存储在本地系统中的证书.我也尝试使用HttpWebRequest获取SSL证书的详细信息,但它要求我输入一个有效的URI,在我的情况下是不可用的.我只有DNS名称

下面是我用HttpWebRequest获取信息的代码.但它要求我输入https://*.domain.com类型的有效URI

Uri uri = new Uri(DNSEntry); 
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(uri); 
request.Method = WebRequestMethods.Http.Get; 
HttpWebResponse response = (HttpWebResponse)request.GetResponse(); 
X509Certificate cert1 = request.ServicePoint.Certificate; 
X509Certificate2 cert = new X509Certificate2(cert1); 
DateTime dtCertExpiry = Convert.ToDateTime(cert.NotAfter.ToString());

解决方法

我尝试使用以下它工作正常:

string strDNSEntry是您需要SSL的DNS

public X509Certificate2 DownloadSslCertificate(string strDNSEntry)
{

    X509Certificate2 cert = null;
    using (TcpClient client = new TcpClient())
    {
        //ServicePointManager.SecurityProtocol = SecurityProtocolType.Ssl3;           
        client.Connect(strDNSEntry,443);

        SslStream ssl = new SslStream(client.GetStream(),false,new RemoteCertificateValidationCallback(ValidateServerCertificate),null);
        try
        {
            ssl.AuthenticateAsClient(strDNSEntry);
        }
        catch (AuthenticationException e)
        {
            log.Debug(e.Message);
            ssl.Close();
            client.Close();
            return cert;
        }
        catch (Exception e)
        {
            log.Debug(e.Message);
            ssl.Close();
            client.Close();
            return cert;
        }
        cert = new X509Certificate2(ssl.RemoteCertificate);
        ssl.Close();
        client.Close();
        return cert;
    }
}


public static bool ValidateServerCertificate(object sender,X509Certificate certificate,X509Chain chain,SslPolicyErrors sslPolicyErrors)
{
    if (sslPolicyErrors == SslPolicyErrors.None)
        return true;

    Console.WriteLine("Certificate error: {0}",sslPolicyErrors);

    // Do not allow this client to communicate with unauthenticated servers. 
    return false;
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读