到目前为止,我能够获得网页SSL证书的到期日期,而我不需要使用用户名&密码:
class Program
{
static void ReadExpirDate()
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create("https://google.com");
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
response.Close();
X509Certificate cert = request.ServicePoint.Certificate;
X509Certificate2 cert2 = new X509Certificate2(cert);
string cedate = cert2.GetExpirationDateString();
Console.WriteLine(cedate);
}
}
但是,如果我尝试获取需要使用用户名和授权进行授权的网页的截止日期。密码才能访问它,我得到一个System.Net.WebException"错误:(401)未经授权"例外。 有没有办法获得SSL证书的到期日期?
答案 0 :(得分:0)
这一行:
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
实际上正在调用未经授权的指定Url,即抛出异常的地方,如果这样做,那么您可以使用返回的Certificate
中的request
属性尽管Exception
:
HttpWebRequest request = (HttpWebRequest)WebRequest.Create("https://google.com");
X509Certificate cert2 = null;
try {
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
X509Certificate cert = request.ServicePoint.Certificate;
X509Certificate2 cert2 = new X509Certificate2(cert);
} catch {
X509Certificate cert = request.ServicePoint.Certificate;
X509Certificate2 cert2 = new X509Certificate2(cert);
} finally {
response.Close();
}
if (cert2 != null) {
string cedate = cert2.GetExpirationDateString();
Console.WriteLine(cedate);
}
此代码将受到一些更好的异常处理和重构,但它应该可以工作。
答案 1 :(得分:0)
使用ServerCertificateValidationCallback
在授权之前获取证书
var request = (HttpWebRequest)WebRequest.Create(GetOptionValue("url"));
request.ServerCertificateValidationCallback += delegate
(object sender, System.Security.Cryptography.X509Certificates.X509Certificate certificate,
System.Security.Cryptography.X509Certificates.X509Chain chain,
System.Net.Security.SslPolicyErrors sslPolicyErrors)
{
string expirationDate = certificate.GetExpirationDateString();
return true;
}