怎么用ssl套接字进行socket连接,以下代码哪里出了问题?
如题。
我用ssl进行socket连接,出错。
错误如下:
[Win32Exception (0x80004005): 处理证书时,出现了一个未知错误。]
[AuthenticationException: 调用 SSPI 失败,请参见内部异常。]
System.Net.Security.SslState.CheckThrow(Boolean authSucessCheck) +1117335
System.Net.Security.SslState.get_SecureStream() +17
System.Net.Security.SslStream.Write(Byte[] buffer) +15
WebApplication4.cnnic.Default.connect() in E:\Visual Studio 2008\Projects\WebApplication4\WebApplication4\cnnic\Default.aspx.cs:72
WebApplication4.cnnic.Default.Page_Load(Object sender, EventArgs e) in E:\Visual Studio 2008\Projects\WebApplication4\WebApplication4\cnnic\Default.aspx.cs:33
System.Web.Util.CalliHelper.EventArgFunctionCaller(IntPtr fp, Object o, Object t, EventArgs e) +15
System.Web.Util.CalliEventHandlerDelegateProxy.Callback(Object sender, EventArgs e) +33
System.Web.UI.Control.OnLoad(EventArgs e) +99
System.Web.UI.Control.LoadRecursive() +47
System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +1061
代码如下:
using System;
using System.Text;
using System.Net.Sockets;
using System.Security.Cryptography.X509Certificates;
using System.Net.Security;
using System.Security.Authentication;
namespace WebApplication4.cnnic
{
public partial class Default : System.Web.UI.Page
{
public Socket skClient;
public string host;
public int port;
private int receiveN;
protected void Page_Load(object sender, EventArgs e)
{
host = "sheep.cnnic.cn";
port = 4121;
connect();
}
public void connect()
{
X509CertificateCollection certs = new X509CertificateCollection();
X509Certificate cert = new X509Certificate(Server.MapPath("/cnnic/szbz02kw.crt"), "szbzszbz");
certs.Add(cert);
TcpClient client = new TcpClient(host, port);
SslStream sslStream = new SslStream(client.GetStream(), false, new RemoteCertificateValidationCallback(ValidateServerCertificate), null);
try
{
sslStream.AuthenticateAsClient(host, certs, SslProtocols.Tls, true);
}
catch (AuthenticationException e)
{
}
byte[] messsage = Encoding.UTF8.GetBytes("Hello from the client.<EOF>");
sslStream.Write(messsage);
sslStream.Flush();
ReadMessage(sslStream);
}
public static bool ValidateServerCertificate(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors)
{
if (sslPolicyErrors == SslPolicyErrors.None)
{
return true;
}
else
{
return false;
}
}
static string ReadMessage(SslStream sslStream)
{
byte[] buffer = new byte[2048];
StringBuilder messageData = new StringBuilder();
int bytes = -1;
do
{
bytes = sslStream.Read(buffer, 0, buffer.Length);
Decoder decoder = Encoding.UTF8.GetDecoder();
char[] chars = new char[decoder.GetCharCount(buffer, 0, bytes)];
decoder.GetChars(buffer, 0, bytes, chars, 0);
messageData.Append(chars);
if (messageData.ToString().IndexOf("<EOF>") != -1)
{
break;
}
} while (bytes != 0);
return messageData.ToString();
}
}
}