C# 判断域名证书是否过期
定义一个基础类
public class DomainName
{
public string GUID { get; set; }
public string Domain { get; set; }
public bool IsChecked { get; set; }
public bool IsExpired { get; set; }
public string Message { get; set; }
public List<string> SupportedSslProtocols { get; set; } = new List<string>();
public string DisplayText
{
get
{
if (IsChecked)
{
return this.Domain + " **** Checked.";
}
else
{
return this.Domain + " **** Unchecked.";
}
}
}
}
调用https请求方法
1 private bool SendHttpRequest(string url) 2 { 3 bool result = false; 4 5 var httpclientHandler = new HttpClientHandler(); 6 7 httpclientHandler.ServerCertificateCustomValidationCallback = (senderx, cert, chain, sslPolicyErrors) 8 => ValidateCertificate(senderx, cert, chain, sslPolicyErrors); 9 10 string domainUrl = url; 11 12 using (var httpClient = new HttpClient(httpclientHandler)) 13 { 14 try 15 { 16 var response = httpClient.GetAsync(domainUrl).Result; 17 18 result = true; 19 } 20 catch (Exception ex) 21 { 22 result = false; 23 } 24 } 25 26 return result; 27 }
检查证书核心代码
private DomainName domainNameEntity = new DomainName();
private bool ValidateCertificate(HttpRequestMessage senderx, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors)
{
bool result = false;
domainNameEntity.IsChecked = true;
var expirationDate = DateTime.Parse(certificate.GetExpirationDateString(), CultureInfo.InvariantCulture);
var effectiveDate = DateTime.Parse(certificate.GetEffectiveDateString(), CultureInfo.InvariantCulture);
if (certificate == null)
{
result = true;
domainNameEntity.IsExpired = false;
domainNameEntity.Message = "The Cert is valid.EffectiveDate : from " + effectiveDate + " to " + expirationDate;
}
else
{
// 已过期
if (expirationDate <= DateTime.Today)
{
domainNameEntity.IsExpired = true;
domainNameEntity.Message = "The Cert has expired.! EffectiveDate : from " + effectiveDate + " to " + expirationDate;
}
//还有十五天过期,则给出提示
else if (expirationDate - DateTime.Today < TimeSpan.FromDays(15))
{
domainNameEntity.IsExpired = false;
domainNameEntity.Message = "It's time to renew the certificate! EffectiveDate : from " + effectiveDate + " to " + expirationDate;
}
//无错误
if (sslPolicyErrors == SslPolicyErrors.None)
{
domainNameEntity.IsExpired = false;
domainNameEntity.Message = "The Cert is valid. EffectiveDate : from " + effectiveDate + " to " + expirationDate;
return true;
}
else
{
domainNameEntity.IsExpired = false;
domainNameEntity.Message = $"Cert errors: {sslPolicyErrors.ToString()}";
}
}
return result;
}

浙公网安备 33010602011771号