我正在编写一个实用程序,它将连接到给定的IP和端口,并使用HttpWebRequest检查SSL证书中的信息。当我尝试提取证书时,我会收到抛出异常的错误。似乎是因为复制SSL证书的行为似乎触发了另一个验证检查。
以下是代码,也许有人可以向我展示更好的方法来完成这项任务,或者告诉我是否遗漏了什么。我不关心SSL证书是否过期或与URL不匹配。对于我的工作来说,这些都不相关。
当我在委托中分配X509Certificate到一个新变量,并在调试器中查看该变量时,所有属性都显示SSLCert.Issuer threw an exception of type 'System.Security.Cryptography.CyrptographicException'
当我尝试访问SSLCert的属性时,我会收到以下异常: m_safeCertContext is an invalid handle
我已经搜索了这个异常,但一切都指向无效的证书,如果证书过期,这可能是真的,并且对于我连接的IP和端口组合也可能是真的。但由于我使用IP连接而不是任何与通用名称匹配的内容,所以我预计会出现这种情况,并且并不在意,因为我仍然需要这些信息。
以下是代码,我还添加了一些注释以说明哪些部分有效和哪些部分无效。
// To get around the SSL validation in the HttpWebRequest
System.Net.ServicePointManager.ServerCertificateValidationCallback =
delegate(object sender, System.Security.Cryptography.X509Certificates.X509Certificate certificate,
System.Security.Cryptography.X509Certificates.X509Chain chain,
System.Net.Security.SslPolicyErrors sslPolicyErrors)
{
// The below works but isn't what I want. CertName and ExpireDate are both Strings
this.CertName = ProcessSubject(certificate.Subject);
this.ExpireDate = certificate.GetExpirationDateString();
// The below works but the X509Certificate SSLCert shows exceptions in the debugger for most of the properties.
this.SSLCert = certificate;
return true; // **** Always accept
};
HttpWebRequest myRequest = (HttpWebRequest)System.Net.WebRequest.Create("https://" + this.IP + ":" + this.Port + "/SSLCheck.html");
myRequest.KeepAlive = false;
myRequest.Method = "GET";
try
{
HttpWebResponse myResponse = (HttpWebResponse)myRequest.GetResponse();
}
catch (Exception e)
{
if (e.Message != "The remote server returned an error: (404) Not Found.")
{
throw Exception("Error");
}
}
// THE BELOW FAILS
this.CertName = this.SSLCert.Subject;
HttpWebRequest
中使用SSL和证书的问题和答案。你看过右边的“相关”问题,或者搜索过[ssl certificate httpwebrequest]吗? - Jim Mischel