我想编写一个使用 tcp 套接字进行通信的客户端和服务器应用程序。但是我不需要证书,因为用户不在乎对方是谁。但我确实需要非对称加密,所以没有人可以窥探。我想不出使用 RSA 共享对称密钥的方法,但无论如何我认为我应该将 SSL 与 TCP 一起使用?
在 C# 中创建 SSL/TCP 连接的最常用方法是什么?我想我要么不指定证书,要么动态创建其中一个(但它们应该是一次性的......)。实现它的最简单方法是什么?我尝试简单地将 sslstream 添加到我的 tcp 流中,但这并没有削减它(我得到流不可读错误)。到目前为止,这是我的简单代码
{
Thread serverThread = new Thread((ThreadStart)delegate
{
TcpListener listener = new TcpListener(1234);
listener.Start();
using (TcpClient client = listener.AcceptTcpClient())
//using (var sslstream = client.GetStream())
using (var sslstream = new System.Net.Security.SslStream(client.GetStream(), true))
using (StreamReader reader = new StreamReader(sslstream))
using (StreamWriter writer = new StreamWriter(sslstream))
{
writer.AutoFlush = true;
string inputLine;
while ((inputLine = reader.ReadLine()) != null)
{
writer.WriteLine(inputLine);
}
}
});
serverThread.Start();
{
string[] linesToSend = new string[] { "foo", "bar", "ack" };
using (TcpClient client = new TcpClient("127.0.0.1", 1234))
//using (var sslstream = client.GetStream())
using (var sslstream = new System.Net.Security.SslStream(client.GetStream(), true))
using (StreamReader reader = new StreamReader(sslstream))
using (StreamWriter writer = new StreamWriter(sslstream))
{
writer.AutoFlush = true;
foreach (string lineToSend in linesToSend)
{
Console.WriteLine("Sending to server: {0}", lineToSend);
writer.WriteLine(lineToSend);
string lineWeRead = reader.ReadLine();
Console.WriteLine("Received from server: {0}", lineWeRead);
//Thread.Sleep(2000); // just for effect
}
Console.WriteLine("Client is disconnecting from server");
}
}
serverThread.Join();
}