目前我正在使用System.Security.Cryptography,这是我的代码:
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);
}
}
}
我准备好通过套接字发送数据时使用它,我创建了一个对象,该对象将在私有字段中具有密钥并且还保持密钥以便它知道密钥,当在另一个客户端上接收到对象时它使用发送的对象内部的函数,该函数使用私有字符串key,key2;并将消息加密为字节并将密钥设置为“”,然后将对象发送回保存字节。所以现在只有原始发件人可以解密它。这是一个很好的方法,还是有更好的方法?
答案 0 :(得分:4)
请勿尝试自行进行加密。
http://msdn.microsoft.com/en-us/library/system.net.security.sslstream.aspx
示例代码使用TcpClient,但它应该适用于任何流IO,因此直接套接字也应该没问题。