2013-03-28 78 views
6

我必須在c#中開發一個應用程序來獲取SSL證書信息,例如基於DNS(例如* .google.com)發佈的等到期日期,等等我提供所以如果到期日期接近,我可以主動處理它。如果我將DNS提供爲* .google.com,那麼我需要獲取該域的SSL ceritificate信息的詳細信息。如何獲取c#中的遠程服務器的SSL證書信息

我試過以下http://awesomeideas.net/page/Cert-Expiry-Check.aspx,但我覺得它是存儲在本地系統中的證書。我也嘗試使用HttpWebRequest來獲取SSL證書的詳細信息,但它要求我輸入一個有效的URI,在我的情況下這是不可用的。我只有DNS名稱

下面是我用來獲取信息使用HttpWebRequest的代碼。但它要求我輸入型HTTPS的有效URI://*.domain.com

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()); 
+0

http://stackoverflow.com/faq#howtoask請閱讀如何問一個問題 – BlackICE

+0

抱歉無法正常發佈的問題的FAQ。我必須在c#中開發一個應用程序來獲取SSL證書信息,如截止日期,基於DNS [say * .google.com]等提供的證書信息,以便如果到期日期接近,我可以主動處理它。如果我將DNS提供爲* .google.com,那麼我需要獲取該域的SSL ceritificate信息的詳細信息 – user166013

+0

您爲了完成此任務而嘗試了哪些內容?你是否需要一個普遍的方向,或者你正在做的事情有困難? – BlackICE

回答

8

我嘗試使用下面這是工作的罰款:

串strDNSEntry是您需要的域名SSL

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; 
} 
相關問題