[英]How to use certificate authentication for custom sockets TCP protocol?
I know that WCF has certificate authentication. 我知道WCF有证书身份验证。 How can I do the same thing for my custom sockets protocol? 如何为自定义套接字协议执行相同的操作? What classes should I use to verify certificates? 我应该使用哪些类来验证证书? What data should I transfer between parties? 我应该在各方之间转移什么数据? What are the required steps? 有哪些必要步骤?
Assuming you want to use SSL: 假设您要使用SSL:
On the server side, you can wrap a NetworkStream
in an SslStream
and authenticate using a X509Certificate
: 在服务器端,您可以将NetworkStream
包装在SslStream
并使用X509Certificate
身份验证:
SslStream stream = new SslStream(networkStream, false);
stream.AuthenticateAsServer(certificate, false, SslProtocols.Default, false);
The false
in that second call controls whether the server requires the client to have a certificate as well. 第二个调用中的false
控制服务器是否还要求客户端拥有证书。
This link contains code to generate a self-signed certificate, handy during development. 此链接包含生成自签名证书的代码,在开发过程中很方便。
On the client side, you have to provide a validation callback: 在客户端,您必须提供验证回调:
SslStream stream = new SslStream(networkStream, false, ValidateRemoteCertificate);
stream.AuthenticateAsClient(RemoteHost);
You can supply client certificates in the AuthenticateAsClient overloads, if desired. 如果需要,您可以在AuthenticateAsClient重载中提供客户端证书。
private bool ValidateRemoteCertificate(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors)
{
if (sslPolicyErrors == SslPolicyErrors.None)
{
return true;
}
// Here you decide whether self-signed certificates are OK
if (allowAnyCertificateAnyway)
{
return true;
}
return false;
}
I hope this helps, it uses NetworkStream
which in the end is simply a wrapper around Socket
. 我希望这会有所帮助,它使用的是NetworkStream
,它最终只是Socket
一个包装器。 This is all built in in the framework, and you can read/write from/to the SslStream
as if it was a regular NetworkStream
. 这都是在框架中内置的,您可以从/向SslStream
读取/写入,就像它是常规的NetworkStream
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.