【发布时间】:2012-06-30 09:19:26
【问题描述】:
我正在编写代码以通过 SSL 连接到远程服务器。我目前使用的代码如下。我收到“根据验证程序,远程证书无效。”
经过一番研究,我发现我必须跳过 SSL 设置的证书验证部分。我应该写什么代码来跳过证书验证?
System.Net.ServicePointManager.ServerCertificateValidationCallback =
(sender, certificate, chain, errors) => true;
TcpClient client = new TcpClient("IPADDDRESSHERE", 80);
Console.WriteLine("Client connected.");
SslStream sslStream = new SslStream(
client.GetStream(),
false,
ValidateServerCertificate,
null
);
try
{
sslStream.AuthenticateAsClient("IPADDDRESSHERE");
}
catch (AuthenticationException e)
{
Console.WriteLine("Exception: {0}", e.Message);
if (e.InnerException != null)
{
Console.WriteLine("Inner exception: {0}", e.InnerException.Message);
}
Console.WriteLine("Authentication failed - closing the connection.");
client.Close();
return;
}
【问题讨论】:
-
"经过一些研究,我发现我必须跳过 SSL 设置的证书验证部分":你没有必须,你也可以做正确的事并选择明确地信任该特定证书。
-
你能告诉我我应该在代码中做什么模组吗?
-
ValidateServerCertificate的定义是什么?
-
public static bool ValidateServerCertificate(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors) { if (sslPolicyErrors == SslPolicyErrors.None) return true; Console.WriteLine("证书错误:{0}", sslPolicyErrors); // 不允许此客户端与未经身份验证的服务器通信。返回真; }
-
成功了。谢谢你的建议