私が取り組んでいる C# .NET Framework 4.5 コードでは、暗号化されたストリームを介してテキストを別のプログラムに転送できるようになっています。私の問題を示すために、2 つの簡単なプログラムを作成しました。EncryptionTestA はサーバーであり、最初に実行することを意図しています。EncryptionTestB はクライアントであり、2 番目に実行することを意図しています。EncryptionTestB が接続すると、CryptoStream を介してテキスト "hello world" を他のプログラムに転送します。少なくとも理論上は。
実際に起こることは何もありません。内部インターフェイスで Wireshark を使用してデータ転送を監視することで、これを確認しました。このコードは、現在の形式ではまったくデータを転送しません。「hello world」を送信する唯一の方法は、クライアント側で StreamWriter を閉じることでした。これに関する問題は、基になる TCP 接続も閉じてしまうことです。これはやりたくないことです。
それで、私の質問: 基になる TCP 接続を閉じずに StreamWriter/CryptoStream をフラッシュするにはどうすればよいですか?
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
using System.Collections;
using System.Threading;
using System.Security;
using System.Security.Cryptography;
using System.Net;
using System.Net.Sockets;
namespace EncryptionTestA
{
class Program
{
static void Main(string[] args)
{
TcpListener listener = new TcpListener(IPAddress.Parse("127.0.0.1"), 1892);
listener.Start();
TcpClient client = listener.AcceptTcpClient();
NetworkStream ns = client.GetStream();
Rijndael aes = RijndaelManaged.Create();
byte[] key = { 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16 };
byte[] iv = { 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16 };
CryptoStream cs = new CryptoStream(ns, aes.CreateDecryptor(key, iv), CryptoStreamMode.Read);
StreamReader sr = new StreamReader(cs);
String test = sr.ReadLine();
Console.Read();
sr.Close();
cs.Close();
ns.Close();
client.Close();
listener.Stop();
}
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
using System.Collections;
using System.Threading;
using System.Security;
using System.Security.Cryptography;
using System.Net;
using System.Net.Sockets;
namespace EncryptionTestB
{
class Program
{
static void Main(string[] args)
{
TcpClient client = new TcpClient();
client.Connect(IPAddress.Parse("127.0.0.1"), 1892);
NetworkStream ns = client.GetStream();
Rijndael aes = RijndaelManaged.Create();
byte[] key = {0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16};
byte[] iv = {0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16};
CryptoStream cs = new CryptoStream(ns, aes.CreateEncryptor(key, iv), CryptoStreamMode.Write);
StreamWriter sw = new StreamWriter(cs);
sw.WriteLine("hello world");
sw.Flush();
//sw.Close();
Console.Read();
sw.Close();
cs.Close();
ns.Close();
client.Close();
}
}
}