currently im using System.Security.Cryptography and this is my code for it:
private static SymmetricAlgorithm createCryptoServiceProvider(string key, string IV)
{
byte[] password;
using (MD5 md5 = MD5.Create())
password = md5.ComputeHash(Encoding.UTF8.GetBytes(key));
var crypt = new TripleDESCryptoServiceProvider();
byte[] iv = Encoding.UTF8.GetBytes(IV);
crypt.IV = iv;
crypt.Key = password;
return crypt;
}
public static byte[] Serialize(object obj, string key, string key2)
{
var provider = createCryptoServiceProvider(key, key2);
using (MemoryStream memory = new MemoryStream())
{
using (CryptoStream stream = new CryptoStream(memory, provider.CreateEncryptor(), CryptoStreamMode.Write))
{
BinaryFormatter formatter = new BinaryFormatter();
formatter.Serialize(stream, obj);
}
return memory.ToArray();
}
}
public static object Deserialize(byte[] inBytes, string key, string key2)
{
var provider = createCryptoServiceProvider(key, key2);
using(MemoryStream memory = new MemoryStream(inBytes))
{
using (CryptoStream stream = new CryptoStream(memory, provider.CreateDecryptor(), CryptoStreamMode.Read))
{
BinaryFormatter formatter = new BinaryFormatter();
return formatter.Deserialize(stream);
}
}
}
i use this when getting ready to send data over a socket, I create a object that will have the key in a private field and also keep the key so it knows the key, when the object is received on the other client then it uses a function inside the object that was sent that uses that private string key, key2; and encrypts the message into bytes and sets the keys to “” and then it sends the object back holding the bytes. so now only the original sender can decrypt it. Is this a good way to do this or is there a better way?
Don’t try to do the encryption yourself.
http://msdn.microsoft.com/en-us/library/system.net.security.sslstream.aspx
The example code uses TcpClient, but it should work with any stream IO, so direct sockets should be fine also.