我遇到了一种情况,我需要加密一个对象才能通过 .NET Remoting 连接发送它以进行传递。我已经在我们的代码中实现了字符串加密,所以我使用了类似的设计来加密对象:
public static byte[] Encrypt(object obj)
{
byte[] bytes = ToByteArray(toEncrypt); // code below
using (SymmetricAlgorithm algo = SymmetricAlgorithm.Create())
{
using (System.IO.MemoryStream ms = new System.IO.MemoryStream())
{
byte[] key = Encoding.ASCII.GetBytes(KEY);
byte[] iv = Encoding.ASCII.GetBytes(IV);
using (CryptoStream cs = new CryptoStream(ms, algo.CreateEncryptor(key, iv), CryptoStreamMode.Write))
{
cs.Write(bytes, 0, bytes.Length);
cs.Close();
return ms.ToArray();
}
}
}
}
private static byte[] ToByteArray(object obj)
{
byte[] bytes = null;
if (obj != null)
{
using (System.IO.MemoryStream ms = new System.IO.MemoryStream())
{
BinaryFormatter bf = new BinaryFormatter();
bf.Serialize(ms, obj);
bytes = ms.ToArray();
}
}
return bytes;
}
通过以这种方式序列化和加密对象,我需要注意什么吗?