最近开发一个需求,涉及获取服务端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); } }}
运行看效果:
650) this.width=650;" src="https://s5.51cto.com/wyfs02/M01/A6/DA/wKioL1ncjAaQ57HSAACWpyaXpHQ820.png" title="未标题-5.png" alt="wKioL1ncjAaQ57HSAACWpyaXpHQ820.png" />
上半部分是程序运行结果,下面是用Firefox查看的服务端证书信息,各项信息都能对应上。如果程序中涉及多个不同服务器的访问也没关系,关键在于根据Uri获取ServicePoint,然后取到的证书就是此服务器的了。
本文出自 “兔子窝” 博客,请务必保留此出处http://boytnt.blog.51cto.com/966121/1971227
获取服务端https证书
原文地址:http://boytnt.blog.51cto.com/966121/1971227