C# 在.net中获取ssl证书

C# 在.net中获取ssl证书,c#,asp.net,ssl,C#,Asp.net,Ssl,我期待着从任何给定的域名SSL证书的数据。例如,我想输入任何网站地址,例如“”,我的代码将首先检查SSL证书是否存在。如果是这样的话,我希望它撤销证书的有效期。[我正在从DB读取域名] 例如: 我需要创建一个web服务来检查到期日期。我如何实施它??-我查找了大量不同的内容,如RequestCertificateValidationCallback和ClientCertificates等 我可能完全错了(因此我需要帮助),但我会创建一个HTTPWebRequest,然后以某种方式请求客户端证书和

我期待着从任何给定的域名SSL证书的数据。例如,我想输入任何网站地址,例如“”,我的代码将首先检查SSL证书是否存在。如果是这样的话,我希望它撤销证书的有效期。[我正在从DB读取域名] 例如:

我需要创建一个web服务来检查到期日期。我如何实施它??-我查找了大量不同的内容,如RequestCertificateValidationCallback和ClientCertificates等

我可能完全错了(因此我需要帮助),但我会创建一个HTTPWebRequest,然后以某种方式请求客户端证书和特定元素吗


我尝试了所提供的示例@,但我遇到了Forbiten 403错误。

要使此工作正常,您的项目将需要对
系统的引用。安全性

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);
.Net核心2.1

您可以使用和属性。(该类在.net 4.7.1及更高版本中也有提供)


需要注意的一点是,您可能需要设置
request.AllowAutoRedirect=False
。否则,如果服务器将HTTPS重定向到HTTP,您将无法从
HttpWebRequest
对象获取证书。

在.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();
}
//使用系统;
//使用System.Net.Http;
//使用System.Security.Cryptography.X509证书;
//使用System.Threading.Tasks;
静态异步任务GetServerCertificateAsync(字符串url)
{
X509Certificate2证书=null;
var httpClientHandler=新的httpClientHandler
{
ServerCertificateCustomValidationCallback=(\u0,证书,\u0,\u0)=>
{
证书=新的X509Certificate2(cert.GetRawCertData());
返回true;
}
};
var httpClient=新的httpClient(httpClientHandler);
等待httpClient.SendAsync(新的HttpRequestMessage(HttpMethod.Head,url));
返回证书??抛出新的NullReferenceException();
}

每次您要发出请求时都重新创建
HttpClient
,这是非常无效的,可能会导致性能问题。最好为所有方法创建一个只读客户端。更多信息可以找到

这是我获取证书信息的解决方案:

构造函数内部的代码:

 _handler = new HttpClientHandler {
    ServerCertificateCustomValidationCallback = (sender, cert, chain, sslPolicyErrors) =>
    {
        sender.Properties.Add("Valid", sslPolicyErrors == System.Net.Security.SslPolicyErrors.None);
        sender.Properties.Add("Errors", sslPolicyErrors);
        return true;
    }
 };
 _client = new HttpClient(_handler);
using var request = new HttpRequestMessage(HttpMethod.Get, "https://www.google.com/");
var response = await _client.SendAsync(request);
var isCertificateValid = (bool)request.Properties["Valid"];
然后您可以通过以下方式读取所有变量:

 _handler = new HttpClientHandler {
    ServerCertificateCustomValidationCallback = (sender, cert, chain, sslPolicyErrors) =>
    {
        sender.Properties.Add("Valid", sslPolicyErrors == System.Net.Security.SslPolicyErrors.None);
        sender.Properties.Add("Errors", sslPolicyErrors);
        return true;
    }
 };
 _client = new HttpClient(_handler);
using var request = new HttpRequestMessage(HttpMethod.Get, "https://www.google.com/");
var response = await _client.SendAsync(request);
var isCertificateValid = (bool)request.Properties["Valid"];

请使用此链接中的详细信息,因为您希望这些链接处理ftp。。。但我已经习惯了,因为我想了解有关证书的详细信息。尝试使用它们来httprequest。我尝试使用httprequest,但我得到了403个禁止的错误,我已经添加了一个答案。请检查一下,让我知道它对你有帮助。cn、cedate、cpubI的打印值我正在aspnetcore 2.1上试用。GET请求成功完成,但
请求.ServicePoint.Certificate
为空@你找到解决办法了吗?@MikkelR.Lund试试这个答案@Poulad啊,太好了。我没看见。这或多或少也是我最终解决它的原因。谢谢。对于.NET3.1,这对我在最后获取证书不起作用;我不得不将
certificate=cert
更改为
certificate=new X509Certificate2(cert.GetRawCertData())
@codeMonkey你太棒了。这是我想要的解决方案,但一开始它不起作用,然后你发布了这个!谢谢,我希望这是公认的解决方案不,你太棒了@Hafiz!❤这也是在.NETCore5中对我有效的解决方案