I'm currently trying to implement a socket server that enables the clients to send some commands to start and stop various services that the server provides. I got the communication between client and server running, and got the server to respond to the commands the clients send. The next step would be to encrypt the communication between client and server. I'm trying to acomplish this with the RSACryptoServiceProvider.
Heres the code i use to enrypt the data:
CspParameters parameter = new CspParameters();
parameter.KeyContainerName = "keycontainer";
rsaProvider = new RSACryptoServiceProvider(parameter);
StreamReader r = new StreamReader(@"C:\tmp\rsakey.xml");
rsaProvider.FromXmlString(r.ReadToEnd());
string command = "server reply goes here";
ASCIIEncoding bc = new ASCIIEncoding();
byte[] cmd = rsaProvider.Encrypt(bc.GetBytes(command), false);
handler.Send(cmd);
And heres the code i use to decrypt my commands
rsaProvider = new RSACryptoServiceProvider(parameter);
StreamReader r = new StreamReader(@"C:\tmp\rsakey.xml");
string xml = r.ReadToEnd();
rsaProvider.FromXmlString(xml);
ASCIIEncoding bc = new ASCIIEncoding();
string test = bc.GetString(state.buffer);
byte[] tmp = rsaProvider.Decrypt(bc.GetBytes(test), false);
I tried directly decrypting my string after I encrypted them, and it works. But the transfer from client to server or the reverse doesn't work and the Decrypt function throws an exception that tells me that the data to decrypt exceeds the maximum for the module.
Whats the correct way to encrypt the traffic between client and server?