Stream Kryptering
HejJeg er ved at prøve at lave en Client/Server hvor stream bliver krypteret. Jeg kan godt sende / modtage ukrypteret men lige så snart jeg prøver at kryptere kan jeg ikke sende, modtage eller begge dele.
Kode til at Sende/Modtage:
private Stream Net()
{
if(Encrypted)
{
CryptoStream SecStream = new CryptoStream(NetStream,TDes.CreateDecryptor(),CryptoStreamMode.Read);
return SecStream;
}
else
return NetStream;
}
public void GetStreamData(IAsyncResult ar)
{
int intCount;
try
{
lock(Net())
{
intCount = Net().EndRead(ar);
}
if(intCount<1)
{
Client.Close();
if(Disconnected!=null)
{
EventArgs e = new EventArgs();
Disconnected(this, e);
}
}
BuildData(recByte,0,intCount);
AsyncCallback GetStreamDataCallback = new AsyncCallback(GetStreamData);
Net().BeginRead(recByte,0,1024,GetStreamDataCallback,null);
}
catch
{
Client.Close();
if(Disconnected!=null)
{
EventArgs e = new EventArgs();
Disconnected(this, e);
}
}
}
private void BuildData(byte[] Databyte, int offset, int count)
{
string Data = Encoding.UTF8.GetString(Databyte, offset, count);
string[] DataCmd = Data.Split(':');
if(!Encrypted)
{
switch(DataCmd[0])
{
case "HELO":
{
Send("Welcome");
break;
}
case "DesKey":
{
TDes.GenerateKey();
DesKey = TDes.Key;
Send("DesKey:" + Convert.ToBase64String(DesKey));
break;
}
case "DesIV":
{
TDes.GenerateIV();
DesIV = TDes.IV;
Send("DesIV:" + Convert.ToBase64String(DesIV));
Encrypted = true;
break;
}
}
}
else
{
Send(Data);
}
}
public void Send(string Data)
{
StreamWriter Writer;
if(Encrypted)
{
CryptoStream SecStream = new CryptoStream(NetStream,TDes.CreateEncryptor(),CryptoStreamMode.Write);
Writer = new StreamWriter(SecStream);
}
else
Writer = new StreamWriter(NetStream);
Writer.Write(Data);
Writer.Flush();
}