C#中的序列化,压缩和加密

时间:2016-01-04 06:54:53

标签: c# encryption serialization stream compression

我想写一个C#类,它可以按顺序序列化,压缩和加密对象。我需要生成的文件

  • 尽可能快地创建
  • 占用尽可能少的空间
  • 尽可能不可读

我已经研究和编码了一段时间,这就是我所拥有的。

    private void SaveObject(string path, object obj)
    {
        using (FileStream fileStream = new FileStream(path, FileMode.Create, FileAccess.Write, FileShare.None))
        {
            string password = "123";
            UnicodeEncoding UE = new UnicodeEncoding();
            byte[] key = UE.GetBytes(password);
            RijndaelManaged RMCrypto = new RijndaelManaged();
            using (CryptoStream cryptoStream = new CryptoStream(fileStream, RMCrypto.CreateEncryptor(key, key), CryptoStreamMode.Write))
            using (var gZipStream = new GZipStream(cryptoStream, CompressionMode.Compress))
            {
                BinaryFormatter binaryFormatter = new BinaryFormatter();
                binaryFormatter.Serialize(gZipStream, obj);
            }
        }
    }

    private void LoadObject(string path, out object obj)
    {
        using (FileStream fileStream = new FileStream(path, FileMode.Open))
        {
            string password = "123"; 
            UnicodeEncoding UE = new UnicodeEncoding();
            byte[] key = UE.GetBytes(password);
            RijndaelManaged RMCrypto = new RijndaelManaged();
            using (CryptoStream cryptoStream = new CryptoStream(fileStream, RMCrypto.CreateDecryptor(key, key), CryptoStreamMode.Read))
            using (var gZipStream = new GZipStream(cryptoStream, CompressionMode.Decompress))
            {
                BinaryFormatter binaryFormatter = new BinaryFormatter();
                obj = binaryFormatter.Deserialize(gZipStream);
            }
        }

    }

我是一名业余程序员,对序列化,流和加密知之甚少。我甚至感到惊讶,这没有问题。我的问题是:这段代码是否遵循最佳编程实践并充分实现目标而不浪费时间或资源?

注意:这是我将在程序中用于在本地存储数据的通用方法。

1 个答案:

答案 0 :(得分:0)

看看https://github.com/HansHinnekint/EncryptionLib。 InfoBlockConvertor代码https://github.com/HansHinnekint/EncryptionLib/blob/master/EncryptionLibrary/InfoBlockConvertor.cs可用作样本。

以后只需要添加压缩。那不应该那么困难。