zoukankan      html  css  js  c++  java
  • C# 获取SSL证书过期时间

    域名不要带https等协议,可以查出来

    using System;
    using System.Net.Security;
    using System.Net.Sockets;
    using System.Security.Authentication;
    using System.Security.Cryptography.X509Certificates;
    
    namespace Demo
    {
        class Program
        {
            static void Main(string[] args)
            {
                var ssl = DownloadSslCertificate("www.baidu.com");
                Console.WriteLine($"过期时间{ssl.NotAfter}");
    
            }
    
            /// <summary>
            /// 获取域名证书
            /// 
            /// </summary>
            /// <param name="strDNSEntry">域名www.baidu.com</param>
            /// <returns></returns>
            public static 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)
                    {
                       
                        ssl.Close();
                        client.Close();
                        return cert;
                    }
                    catch (Exception e)
                    {
                        
                        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;
            }
    
        }
    }
  • 相关阅读:
    hdu1686 最大匹配次数 KMP
    洛谷 P5057 [CQOI2006]简单题(树状数组)
    洛谷 P5020 货币系统
    洛谷 P5019 铺设道路(差分)
    洛谷 P1119 灾后重建(Floyd)
    洛谷 P1082 同余方程(同余&&exgcd)
    洛谷 P2384 最短路
    洛谷 P3371 【模板】单源最短路径(弱化版) && dijkstra模板
    洛谷 P1387 最大正方形
    洛谷 P2866 [USACO06NOV]糟糕的一天Bad Hair Day
  • 原文地址:https://www.cnblogs.com/cvol/p/15088631.html
Copyright © 2011-2022 走看看