我正在编写一个程序,用于从用户提供的URL中读取内容。我的问题在于代码是这样的:
Uri uri = new Uri(url);
WebRequest webRequest = WebRequest.Create(uri);
WebResponse webResponse = webRequest.GetResponse();
ReadFrom(webResponse.GetResponseStream());
如果提供的 url 是“https://”网址,则会中断。任何人都可以帮助我更改此代码,以便它可以使用SSL加密的内容。感谢。
答案 0 :(得分:166)
您正在以正确的方式执行此操作,但用户可能会向安装了无效SSL证书的网站提供网址。如果在发出实际Web请求之前放入此行,则可以忽略这些证书问题:
ServicePointManager.ServerCertificateValidationCallback = new System.Net.Security.RemoteCertificateValidationCallback(AcceptAllCertifications);
其中AcceptAllCertifications
定义为
public bool AcceptAllCertifications(object sender, System.Security.Cryptography.X509Certificates.X509Certificate certification, System.Security.Cryptography.X509Certificates.X509Chain chain, System.Net.Security.SslPolicyErrors sslPolicyErrors)
{
return true;
}
答案 1 :(得分:18)
您可能会对此链接感兴趣:http://msdn.microsoft.com/en-us/library/ds8bxk2a.aspx
对于http连接,WebRequest和WebResponse类使用SSL与支持SSL的Web主机进行通信。决定使用SSL是由WebRequest类根据给定的URI做出的。如果URI以“https:”开头,则使用SSL;如果URI以“http:”开头,则使用未加密的连接。
答案 2 :(得分:13)
这个对我有用:
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
答案 3 :(得分:0)
正如@LukeDuff 投票最多的答案所说的那样,可能是服务器使用了无效或不受信任(或自签名,技术上也不受信任)的证书。但答案盲目接受任何证书。更糟糕的是,即使是任何站点的任何证书,甚至对于您期望可信且有效证书的站点也是如此。这是一个安全漏洞。
在实施 ServicePointManager.ServerCertificateValidation
callback 时,应该验证证书。例如。通过根据已知值检查证书的哈希值:
using System.Net;
using System.Net.Security;
using System.Security.Cryptography;
ServicePointManager.ServerCertificateValidationCallback +=
(sender, certificate, chain, errors) =>
{
return
(errors == SslPolicyErrors.None) ||
certificate.GetCertHashString(HashAlgorithmName.SHA256).Equals(
"EB8E0B28AE064ED58CBED9DAEB46CFEB3BD7ECA67737179E3C85BC3CD09D4EEC");
};
对于 X509Certificate.GetCertHashString
overload that takes HashAlgorithmName.SHA256
,您需要 .NET 4.8。在旧版本上使用 the parameter-less overload 返回一个 SHA-1 哈希值。
有关 VB.NET 版本的代码,请参阅 Accept self-signed TLS/SSL certificate in VB.NET。