C# - Serializing/Deserializing a DES encrypted file from a stream

后端 未结 3 829
感动是毒
感动是毒 2020-12-14 04:28

Does anyone have any examples of how to encrypt serialized data to a file and then read it back using DES?

I\'ve written some code already that isn\'t working, but I

3条回答
  •  失恋的感觉
    2020-12-14 05:03

    This thread gave the basic idea. Here's a version that makes the functions generic, and also allows you to pass an encryption key so it's reversible.

    public static void EncryptAndSerialize(string filename, T obj, string encryptionKey) {
      var key = new DESCryptoServiceProvider();
      var e = key.CreateEncryptor(Encoding.ASCII.GetBytes("64bitPas"), Encoding.ASCII.GetBytes(encryptionKey));
      using (var fs = File.Open(filename, FileMode.Create))
      using (var cs = new CryptoStream(fs, e, CryptoStreamMode.Write))
          (new XmlSerializer(typeof (T))).Serialize(cs, obj);
    }
    
    public static T DecryptAndDeserialize(string filename, string encryptionKey) {
      var key = new DESCryptoServiceProvider();
      var d = key.CreateDecryptor(Encoding.ASCII.GetBytes("64bitPas"), Encoding.ASCII.GetBytes(encryptionKey));
      using (var fs = File.Open(filename, FileMode.Open))
      using (var cs = new CryptoStream(fs, d, CryptoStreamMode.Read))
          return (T) (new XmlSerializer(typeof (T))).Deserialize(cs);
    }
    

提交回复
热议问题