我希望从任何给定的域名SSL证书获取数据.例如,我想放入任何网站地址,例如" http://stackoverflow.com ",我的代码将首先检查是否存在SSL证书.如果确实如此,我希望它能够取出证书的失效日期.[我正在阅读DB的Domainnames]示例:http://www.digicert.com/help/
我需要创建一个Web服务来检查到期日期.我怎么能实现它? - 我查了很多不同的东西,比如RequestCertificateValidationCallback和ClientCertificates等.
我可能完全错了(因此我需要帮助)但是我会创建一个HTTPWebRequest然后以某种方式请求客户端证书和特定元素吗?
我尝试了提供@ SSL证书预取.NET的示例,但我得到了forbitten 403错误.
cde*_*dev 26
为此,您的项目需要参考System.Security
:
using System.Security;
using System.Security.Cryptography;
using System.Security.Cryptography.X509Certificates;
//Do webrequest to get info on secure site
HttpWebRequest request = (HttpWebRequest)WebRequest.Create("https://mail.google.com");
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
response.Close();
//retrieve the ssl cert and assign it to an X509Certificate object
X509Certificate cert = request.ServicePoint.Certificate;
//convert the X509Certificate to an X509Certificate2 object by passing it into the constructor
X509Certificate2 cert2 = new X509Certificate2(cert);
string cn = cert2.GetIssuerName();
string cedate = cert2.GetExpirationDateString();
string cpub = cert2.GetPublicKeyString();
//display the cert dialog box
X509Certificate2UI.DisplayCertificate(cert2);
Run Code Online (Sandbox Code Playgroud)
Pou*_*lad 13
@cdev 的解决方案在 .NET Core 2.1 上对我不起作用。这似乎HttpWebRequest
是不完全支持.NET的核心。
这是我在 .NET Core 上用来获取任何服务器的 X509 证书的函数:
// using System;
// using System.Net.Http;
// using System.Security.Cryptography.X509Certificates;
// using System.Threading.Tasks;
static async Task<X509Certificate2> GetServerCertificateAsync(string url)
{
X509Certificate2 certificate = null;
var httpClientHandler = new HttpClientHandler
{
ServerCertificateCustomValidationCallback = (_, cert, __, ___) =>
{
certificate = new X509Certificate2(cert.GetRawCertData());
return true;
}
};
var httpClient = new HttpClient(httpClientHandler);
await httpClient.SendAsync(new HttpRequestMessage(HttpMethod.Head, url));
return certificate ?? throw new NullReferenceException();
}
Run Code Online (Sandbox Code Playgroud)
小智 5
需要注意的一件事是您可能需要设置request.AllowAutoRedirect = False
. 否则,如果服务器将 HTTPS 重定向到 HTTP,您将无法从HttpWebRequest
对象获取证书。