编辑:MSDN 在此页面底部有一个完整的工作示例:https://msdn.microsoft.com/en-us/library/system.net.security.sslstream?f=255&MSPPError=-2147217396 - 所以您应该真正开始在那里进行试验,因为该示例包含所有内容。
原答案:
我必须先回答“不需要客户端身份验证”是大多数 SSL 实现的情况。客户端身份验证很少见:您可能会在 VPN 应用、银行业和其他安全应用中看到它。因此,当您尝试使用 SslStream() 时,最好在没有客户端身份验证的情况下启动。
当您浏览 HTTPS 网站时,您不会使用客户端证书对浏览器进行身份验证,而只是想确认您要连接的服务器名称与证书中找到的 CNAME 匹配,并且服务器证书由您的机器信任的 CA 签名 - 它还有更多内容,但本质上就是它归结为的内容。
那么,说了这么多,让我来回答你的问题:
1) SslStream.AuthenticateAsServer(...) 仅在服务器端使用服务器 509 证书完成。在客户端,您必须调用SslStream.AuthenticateAsClient(serverName),服务器名称是您证书的 CNAME(通用名称)(例如:“domain.com”)
2) 必须为客户端和服务器创建SslStream。您只需通过“包装”一个 TcpClient NetworkStream 来创建它(例如,但还有其他方法)
服务器示例:
// assuming an 509 certificate has been loaded before in an init method of some sort
X509Certificate serverCertificate = X509Certificate2.CreateFromCertFile("c:\\mycert.cer"); // for illustration only, don't do it like this in production
...
// assuming a TcpClient tcpClient was accepted somewhere above this code
slStream sslStream = new SslStream(tcpClient.GetStream(), false);
sslStream.AuthenticateAsServer(
serverCertificate,
false,
SslProtocols.Tls,
true);
3) 不可以。通信在两端都被加密。所以双方必须使用SslStream。在客户端上使用receive() 和send() 会产生二进制加密数据。
4) 否。客户端将回调方法传递给SslStream 创建,以验证服务器收到的证书。
例子:
// assuming a TcpClient tcpClient was connected to the server somewhere above this code
SslStream sslStream = new SslStream(
tcpClient.GetStream(),
false,
new RemoteCertificateValidationCallback(ValidateServerCertificate),
null
);
sslStream.AuthenticateAsClient(serverName); // serverName: "domain.com" for example
然后在您的代码中的其他地方:
public static bool ValidateServerCertificate(
object sender,
X509Certificate certificate,
X509Chain chain,
SslPolicyErrors sslPolicyErrors)
{
if (sslPolicyErrors == SslPolicyErrors.None) {
return true;
}
Console.WriteLine("Certificate error: {0}", sslPolicyErrors);
// refuse connection
return false;
}