C#从ServerCertificateValidationCallback获取SMTP服务器的SSL证书过期日期作为返
本文关键字:过期 证书 日期 SSL ServerCertificateValidationCallback 获取 SMTP 服务器 | 更新日期: 2023-09-27 17:58:33
目前我有以下代码来获取SMTP服务器的到期日期:
命名空间SMTPCert{公共类SMTPCert{公共静态void GetSMTPCert(字符串ServerName){ServicePointManager。ServerCertificateValidationCallback=新的RemoteCertificateValidation回调(RemoteServerCertificateValidation回调);使用(System.Net.Mail.SmtpClient S=新的System.Net.Mail.SmtpCClient(ServerName)){S.EnableSsl=true;使用(System.Net.Mail.MailMessage M=新的System.Net.Mail.MailMessage("test@example.com","test@example.com","测试","试验"){尝试{S.Send(M);}catch(异常){回来}}}}
private static bool RemoteServerCertificateValidationCallback(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors)
{
Console.WriteLine(certificate);
return true;
}
}
}
我的问题是,我想将GetSMTPCert方法从void更改为string,以便将证书到期日期返回到我的主方法。但目前我只能在RemoteServerCertificateValidationCallback方法中获取到期日期,无法从中返回。有没有任何可能的方法可以将证书过期日期获取到我的GetSMTPCert方法,然后将其返回到我的主方法?
我们也欢迎有关获取SMTP服务器SSL证书到期日期的其他方法的建议。
好的,我通过将字符串类型为"CertificateDaysLeft"的公共静态字段添加到我的SMTPCert类中解决了这个问题。
namespace SMTPCert
{
public static string CertificateDaysLeft;
public static string GetSMTPCert(string ServerName)
{
ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(RemoteServerCertificateValidationCallback);
using (System.Net.Mail.SmtpClient S = new System.Net.Mail.SmtpClient(ServerName))
{
S.EnableSsl = true;
using (System.Net.Mail.MailMessage M = new System.Net.Mail.MailMessage("test@example.com", "test@example.com", "Test", "Test"))
{
try
{
S.Send(M);
string daysLeft = CertificateDaysLeft;
return daysLeft;
}
catch (Exception)
{
string daysLeft = CertificateDaysLeft;
return daysLeft;
}
}
}
}
private static bool RemoteServerCertificateValidationCallback(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors)
{
DateTime ExpirDate = Convert.ToDateTime(certificate.GetExpirationDateString());
string DaysLeft = Convert.ToString((ExpirDate - DateTime.Today).Days);
CertificateDaysLeft = DaysLeft;
Console.WriteLine(certificate);
return true;
}
}
}
我想我想得有点太复杂了。