C# 在 .net 中获取 ssl 证书

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15270764/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 16:12:30  来源:igfitidea点击:

get ssl certificate in .net

c#asp.netssl

提问by user166013

i am looking to get the data from any given domain names SSL certificate. For example I want to put in any website address e.g. "http://stackoverflow.com" and my code would firstly check if an SSL certificate exists. If it does then I want it to pull out the expiry date of the certificate. [ i am reading Domainnames from DB ] Example :http://www.digicert.com/help/

我希望从任何给定的域名 SSL 证书中获取数据。例如,我想输入任何网站地址,例如“ http://stackoverflow.com”,我的代码将首先检查 SSL 证书是否存在。如果是这样,那么我希望它提取证书的到期日期。[我正在从数据库读取域名] 示例:http: //www.digicert.com/help/

i need to create a web service to check expiry date. how can i implement it?? - I have looked up loads of different things such as RequestCertificateValidationCallback and ClientCertificates etc.

我需要创建一个网络服务来检查到期日期。我该如何实施?- 我查了很多不同的东西,比如 RequestCertificateValidationCallback 和 ClientCertificates 等。

I could be completely wrong (hence why I need help) but would I create a HTTPWebRequest and then somehow request the client certificate and specific elements that way?

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

i tried the example provided @SSL certificate pre-fetch .NET, but i am getting forbitten 403 error.

我尝试了@ SSL 证书预取 .NET提供的示例,但我收到了禁止 403 错误。

采纳答案by cdev

For this to work your project will need a reference to System.Security:

为此,您的项目需要参考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);

.Net Core 2.1

.Net 核心 2.1

You can use HttpClientHandlerand ServerCertificateCustomValidationCallbackProperty. (This class is available in .net 4.7.1 and above also).

您可以使用HttpClientHandlerServerCertificateCustomValidationCallback属性。(此类在 .net 4.7.1 及更高版本中也可用)。

var handler = new HttpClientHandler
{
     UseDefaultCredentials = true,

     ServerCertificateCustomValidationCallback = (sender, cert, chain, error) =>
     {

          /// Access cert object.

          return true;
     }
 };

 using (HttpClient client = new HttpClient(handler))
 {
     using (HttpResponseMessage response = await client.GetAsync("https://mail.google.com"))
     {
          using (HttpContent content = response.Content)
          {

          }
      }
 }

回答by user60177

One thing to note is that you might need to set request.AllowAutoRedirect = False. Otherwise, if the server redirects HTTPS to HTTP, you won't be able to get the certificate from the HttpWebRequestobject.

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

回答by Poulad

@cdev's solutiondidn't work for me on .NET Core 2.1. It seems HttpWebRequestis not completely supportedon .NET Core.

@cdev 的解决方案在 .NET Core 2.1 上对我不起作用。这似乎HttpWebRequest不完全支持.NET的核心。

Here is the function I'm using on .NET Coreto get any server's X509 certificate:

这是我在 .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();
}