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

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

概述我必须在c#中开发一个应用程序,以获取基于我提供的DNS(例如* .google.com)发布的SSL证书信息,如有效期,以便如果到期日期临近,我可以主动处理它.如果我将DNS提供为* .google.com,那么我需要获取该域的SSL证书信息的详细信息. 我试过跟随http://awesomeideas.net/page/Cert-Expiry-Check.aspx,但我觉得它是存储在本地系统中 我必须在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;}
总结

以上是内存溢出为你收集整理的如何在c#中获取远程服务器的SSL证书信息全部内容,希望文章能够帮你解决如何在c#中获取远程服务器的SSL证书信息所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址:https://54852.com/langs/1249872.html

(0)
打赏 微信扫一扫微信扫一扫 支付宝扫一扫支付宝扫一扫
上一篇 2022-06-07
下一篇2022-06-07

发表评论

登录后才能评论

评论列表(0条)

    保存