【问题标题】:get ssl certificate in .net在 .net 中获取 ssl 证书
【发布时间】:2013-02-22 15:01:44
【问题描述】:

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

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

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

我尝试了@SSL certificate pre-fetch .NET 提供的示例,但出现了 403 错误。

【问题讨论】:

  • 请根据需要使用此链接中的详细信息stackoverflow.com/questions/1534908/…codeproject.com/Articles/31624/… 这些链接处理 ftp...但我使用它们是因为我想获取有关证书的详细信息。尝试使用它们来进行 httprequest。
  • 我尝试使用 httprequest 但我收到 403 禁止错误
  • 我已经添加了一个答案。请检查一下,让我知道它对您有帮助。

标签: c# asp.net ssl


【解决方案1】:

为此,您的项目需要引用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 5

您可以使用HttpClientHandler 和ServerCertificateCustomValidationCallback 属性。 (此类在 .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)
          {

          }
      }
 }

【讨论】:

  • 打印cn、cedate、cpub的值
  • 我正在 aspnetcore 2.1 上尝试它。 GET 请求成功完成但request.ServicePoint.Certificate 为空!
  • @Poulad 你找到解决方案了吗?
  • @MikkelR.Lund 试试这个答案stackoverflow.com/a/54063971/5755313
  • @Poulad 啊,太好了。没见过。这或多或少也是我最终解决它的方式。谢谢。
【解决方案2】:

@cdev's solution 在 .NET Core 2.1 上对我不起作用。在 .NET Core 上,HttpWebRequest 似乎是 not completely supported。

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

【讨论】:

  • 对于.NET 3.1,这对我最后获取证书不起作用;我不得不将certificate = cert 更改为certificate = new X509Certificate2(cert.GetRawCertData())
  • @codeMonkey 你太棒了。这是我想要的解决方案,它最初不起作用,然后你发布了这个!谢谢,我希望这是公认的解决方案
  • 不,你太棒了@Hafiz! ❤
  • 这也是在 .net core 5 中对我有用的解决方案
  • 有些网站不接受 HttpMethod.Head。您可以改用 HttpMethod.Get,但速度会稍慢。
【解决方案3】:

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

【讨论】:

    【解决方案4】:

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

    private readonly HttpClientHandler _handler;
    private readonly HttpClient _client;
    

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

    构造函数内的代码:

     _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"];
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-01-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-04-28
      • 2015-08-10
      相关资源
      最近更新 更多