4

我使用下面给出的函数将我的 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
        }
    }

非常感谢任何帮助。

谢谢

4

1 回答 1

2

使用以下给定的类加密/解密您的流式 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;
  }
}
于 2013-09-04T15:02:22.080 回答