C#中对象的加密序列化

本文关键字:加密 序列化 对象 | 更新日期: 2023-09-27 18:30:13

我使用下面给出的函数将DataTable存储在一个文件中,该函数是我从网站上获得的。代码运行良好。

问题是:

我想在这里应用某种加密。我怎样才能做到这一点

    public void SerializeObject<T>(T serializableObject, string fileName)
    {
        if (serializableObject == null) { return; }
        try
        {
            XmlDocument xmlDocument = new XmlDocument();
            XmlSerializer serializer = new XmlSerializer(serializableObject.GetType());
            using (MemoryStream stream = new MemoryStream())
            {
                serializer.Serialize(stream, serializableObject);
                stream.Position = 0;
                xmlDocument.Load(stream);
                xmlDocument.Save(fileName);
                stream.Close();
            }
        }
        catch (Exception ex)
        {
            //Log exception here
        }
    }

非常感谢您的帮助。

感谢

C#中对象的加密序列化

使用以下给定的类加密/解密流式XML文件:根据您的要求,您可以使用另一种加密策略。

public static class EncryptionManagement
{
  private static SymmetricAlgorithm encryption;
  private const string password = "admin";
  private const string Mkey = "MY SECRET KEY";
  private static void Init()
  {
    encryption = new RijndaelManaged();
    var key = new Rfc2898DeriveBytes(password, Encoding.ASCII.GetBytes(Mkey));
    encryption.Key = key.GetBytes(encryption.KeySize / 8);
    encryption.IV = key.GetBytes(encryption.BlockSize / 8);
    encryption.Padding = PaddingMode.PKCS7;
  }
  public static void Encrypt(Stream inStream, Stream OutStream)
  {
    Init();
    var encryptor = encryption.CreateEncryptor();
    inStream.Position = 0;
    var encryptStream = new CryptoStream(OutStream, encryptor, CryptoStreamMode.Write);
    inStream.CopyTo(encryptStream);
    encryptStream.FlushFinalBlock();
  }

  public static void Decrypt(Stream inStream, Stream OutStream)
  {
    Init();
    var encryptor = encryption.CreateDecryptor();
    inStream.Position = 0;
    var encryptStream = new CryptoStream(inStream, encryptor, CryptoStreamMode.Read);
    encryptStream.CopyTo(OutStream);
    OutStream.Position = 0;
  }
}