獲取服務端https證書


最近開發一個需求,涉及獲取服務端https證書。一般進行https調用我們都不太關心底層細節,直接使用WebClient或者HttpWebRequest來發送請求,這兩種方法都無法獲取證書信息,需要用到ServicePoint,這個類用於提供HTTP連接的管理。

 

寫個Demo,拿新浪首頁試一下:

復制代碼
using System;
using System.Net;
using System.Security.Cryptography.X509Certificates;
 
namespace GetServerCertificateDemo
{
    class Program
    {
        static void Main(string[] args)
        {
            //用WebClient訪問新浪首頁
            var http = new WebClient();
            var uri = new Uri("https://www.sina.com.cn");
            http.DownloadString(uri);
             
            //通過Uri獲取ServicePoint
            var servicePoint = ServicePointManager.FindServicePoint(uri);
             
            //取服務端證書,X509Certificate格式,轉一下
            var serverCert = new X509Certificate2(servicePoint.Certificate);
            Console.WriteLine("頒發給:{0}", serverCert.Subject);
            Console.WriteLine("頒發者:{0}", serverCert.Issuer);
            Console.WriteLine("序列號:{0}", serverCert.SerialNumber);
            Console.WriteLine("指  紋:{0}", serverCert.Thumbprint);
            Console.WriteLine("起  始:{0}", serverCert.NotBefore);
            Console.WriteLine("過  期:{0}", serverCert.NotAfter);
        }
    }
}
復制代碼

 

運行看效果:

上半部分是程序運行結果,下面是用Firefox查看的服務端證書信息,各項信息都能對應上。如果程序中涉及多個不同服務器的訪問也沒關系,關鍵在於根據Uri獲取ServicePoint,然后取到的證書就是此服務器的了。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM