小编omn*_*lex的帖子

如何在C#中使用带有HttpWebRequest的SSL证书?

目前我正在编写一个实用程序应用程序,它将连接到给定的IP和端口,并使用HttpWebRequest检查SSL证书中的信息.当我尝试提取证书时,我收到一个错误,即抛出异常.例外似乎是因为应对SSL证书的行为似乎触发了另一个验证检查.

这是代码,也许有人可以告诉我一个更好的方法来做到这一点,或者我错过了什么.我不在乎SSL证书是否已过期或与URL不匹配.这些都与我正在做的事情无关.

当我将委托中的X509Certificate分配给一个新变量,并查看调试器中的变量时,所有属性都显示SSLCert.Issuer抛出类型为'System.Security.Cryptography.CyrptographicException'的异常

当我尝试访问SSLCert的属性时,我得到以下抛出的异常:m_safeCertContext是一个无效的句柄

我搜索了这个异常,但是所有内容都指向一个无效的证书,如果证书过期,则可能是真的,对于我连接的IP和端口组合可能都是如此.但由于我使用IP连接到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 …
Run Code Online (Sandbox Code Playgroud)

c# ssl httpwebrequest x509certificate x509

8
推荐指数
1
解决办法
1万
查看次数

标签 统计

c# ×1

httpwebrequest ×1

ssl ×1

x509 ×1

x509certificate ×1