如何使用 WebRequest 访问使用 HTTPS 的 SSL 加密站点?
我正在编写一个从用户提供的 URL 读取内容的程序。 我的问题出在类似这样的代码中:
Uri uri = new Uri(url);
WebRequest webRequest = WebRequest.Create(uri);
WebResponse webResponse = webRequest.GetResponse();
ReadFrom(webResponse.GetResponseStream());
如果提供的 url 是 https://
URL,则这会破坏。 任何人都可以帮助我更改此代码,以便它可以与 SSL 加密的内容一起使用。 谢谢。
I'm writing a program that reads content from a user provided URL. My problem is in the code that goes something like this:
Uri uri = new Uri(url);
WebRequest webRequest = WebRequest.Create(uri);
WebResponse webResponse = webRequest.GetResponse();
ReadFrom(webResponse.GetResponseStream());
And this is breaking if the provided url is an https://
URL. Can anyone help me with changing this code so that it will work with SSL encrypted content. Thanks.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您的操作方式正确,但用户可能会提供指向安装了无效 SSL 证书的网站的 URL。 如果您在发出实际的 Web 请求之前放入此行,则可以忽略这些证书问题:
其中
AcceptAllCertifications
定义为You're doing it the correct way but users may be providing urls to sites that have invalid SSL certs installed. You can ignore those cert problems if you put this line in before you make the actual web request:
where
AcceptAllCertifications
is defined as这对我有用:
This one worked for me:
您可能会对以下链接感兴趣:http://msdn.microsoft.com/ en-us/library/ds8bxk2a.aspx
This link will be of interest to you: http://msdn.microsoft.com/en-us/library/ds8bxk2a.aspx
正如@LukeDuff 投票最多的答案所正确指出的那样,服务器很可能使用无效或不受信任(或自签名,技术上也是不受信任)的证书。 但答案盲目接受任何证书。 更糟糕的是,甚至是任何站点的任何证书,甚至是您期望可信且有效的证书的站点。 这是一个安全缺陷。
实施
ServicePointManager.ServerCertificateValidation
时回调应该验证证书。 例如,通过根据已知值检查证书的哈希值:对于
X509Certificate.GetCertHashString
重载采用HashAlgorithmName.SHA256
,您需要.NET 4.8。 在旧版本上使用 返回 SHA-1 哈希值的无参数重载。基于当您知道无效证书是安全时测试 X509Certificate.Thumbprint 属性是否安全?
对于 VB.NET 版本的代码,请参阅在 VB.NET 中接受自签名 TLS/SSL 证书< /a>。
As the most voted answer by @LukeDuff correctly says, it is probable that the server uses an invalid or untrusted (or self-signed, what is technically also untrusted) certificate. But the answer blindly accepts any certificate. And what's worse, even any certificate for any site, even for sites, where you expect trusted and valid certificate. That's a security flaw.
When implementing
ServicePointManager.ServerCertificateValidation
callback one should validate the certificate. E.g. by checking certificate's hash against a known value:For the
X509Certificate.GetCertHashString
overload that takesHashAlgorithmName.SHA256
, you need .NET 4.8. On older versions use the parameter-less overload that returns an SHA-1 hash.Based on Is it safe to test the X509Certificate.Thumbprint property when you know an invalid certificate is safe?
For VB.NET version of the code, see Accept self-signed TLS/SSL certificate in VB.NET.