溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點(diǎn)擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

獲取服務(wù)端https證書

發(fā)布時(shí)間:2020-05-24 17:34:50 來源:網(wǎng)絡(luò) 閱讀:1817 作者:BoyTNT 欄目:編程語言

最近開發(fā)一個(gè)需求,涉及獲取服務(wù)端https證書。一般進(jìn)行https調(diào)用我們都不太關(guān)心底層細(xì)節(jié),直接使用WebClient或者HttpWebRequest來發(fā)送請求,這兩種方法都無法獲取證書信息,需要用到ServicePoint,這個(gè)類用于提供HTTP連接的管理。


寫個(gè)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);
            
            //取服務(wù)端證書,X509Certificate格式,轉(zhuǎn)一下
            var serverCert = new X509Certificate2(servicePoint.Certificate);
            Console.WriteLine("頒發(fā)給:{0}", serverCert.Subject);
            Console.WriteLine("頒發(fā)者:{0}", serverCert.Issuer);
            Console.WriteLine("序列號:{0}", serverCert.SerialNumber);
            Console.WriteLine("指  紋:{0}", serverCert.Thumbprint);
            Console.WriteLine("起  始:{0}", serverCert.NotBefore);
            Console.WriteLine("過  期:{0}", serverCert.NotAfter);
        }
    }
}


運(yùn)行看效果:

獲取服務(wù)端https證書


上半部分是程序運(yùn)行結(jié)果,下面是用Firefox查看的服務(wù)端證書信息,各項(xiàng)信息都能對應(yīng)上。如果程序中涉及多個(gè)不同服務(wù)器的訪問也沒關(guān)系,關(guān)鍵在于根據(jù)Uri獲取ServicePoint,然后取到的證書就是此服務(wù)器的了。



向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI