Moons
Moons

Reputation: 3854

Encrypted Serialization of Objects in C#

I am storing my DataTable in a file using the function given below which i had taken from a website. The code works well.

The problem is:

I want to apply some sort of encryption here. How can i achieve that?

    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 highly appreciated.

Thanks

Upvotes: 4

Views: 6774

Answers (1)

Bassam Alugili
Bassam Alugili

Reputation: 17003

Encrypt/Decrypt your streamed XML file with the given below class: You can use another encryption strategy it is depending 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;
  }
}

Upvotes: 2

Related Questions