Encrypted serialization of objects in C #

I save my DataTable to a file using the function below, which I took from the website. The code works well.

The problem is this:

I want to apply some kind of encryption here. How can I achieve this?

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 } } 

Any help is appreciated.

thanks

+4
source share
1 answer

Encrypt / decrypt XML stream file with the following class: You can use a different encryption strategy, which depends on your requirements.

 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; } } 
+1
source

Source: https://habr.com/ru/post/1500562/


All Articles