在.net中获取ssl证书

qxgroojn  于 2023-06-06  发布在  .NET
关注(0)|答案(4)|浏览(602)

我期待着从任何给定的域名SSL证书的数据。例如,我想输入任何网站地址。“http://stackoverflow.com”,我的代码将首先检查是否存在SSL证书。如果是的话,我希望它能把证书的到期日期拉出来。[ i am阅读Domainnames from DB ]示例:http://www.digicert.com/help/
我需要创建一个Web服务来检查到期日期。我怎样才能实施呢??-我查了很多不同的东西,比如RequestCertificateValidationCallback和ClientCertificates等。
我可能完全错了(因此我需要帮助),但我会创建一个HTTPWebRequest,然后以某种方式请求客户端证书和特定元素吗?
我尝试了@SSL certificate pre-fetch .NET提供的示例,但我得到了禁止403错误。

tf7tbtn2

tf7tbtn21#

要做到这一点,你的项目需要引用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

您可以使用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)
          {

          }
      }
 }
rekjcdws

rekjcdws2#

@cdev的解决方案在.NET Core 2.1上不适用。HttpWebRequest在.NET Core上是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();
}
ycggw6v2

ycggw6v23#

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

nhn9ugyo

nhn9ugyo4#

每次要发出请求时都重新创建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"];

相关问题