-3

I use Serialize function to save an object to hard disk by the following code:

using (FileStream fs = new FileStream(fileName, FileMode.Create))
                    new BinaryFormatter().Serialize(fs, myObject);

Then I reload it again when I need it:

using(FileStream fs = new FileStream(fileName, FileMode.Open))
                    myObject = (Templates)new BinaryFormatter().Deserialize(fs);

I'm searching an easy way to encrypt the file I save to protect it and also fast way because the time factor in saving and reading the file is very important.

Any suggestions please, thank you in advance!

  • https://www.google.co.uk/search?q=C%23+encrypt+file&oq=C%23+encrypt+file&aqs=chrome..69i57j69i58j0l4.2538j0j7&sourceid=chrome&ie=UTF-8 contains a lot of useful-looking results. Did you try any of them? – ADyson Sep 04 '17 at 17:51
  • @ADyson Thank you, I'm taking a look – Waleed ELerksosy Sep 04 '17 at 17:52
  • So you think your encryption and decryption will take significantly more time then your file I/O? – rene Sep 04 '17 at 17:54
  • @rene I've no idea how to do encryption and decryption for the file. – Waleed ELerksosy Sep 04 '17 at 17:57
  • You could use `CryptoStream`. See [C# Encrypt serialized file before writing to disk](https://stackoverflow.com/a/5870397/3744182) or [C# - Serializing/Deserializing a DES encrypted file from a stream](https://stackoverflow.com/q/965042/3744182). – dbc Sep 04 '17 at 17:59
  • @dbc Thank you these links helped me a lot! – Waleed ELerksosy Sep 04 '17 at 18:02

1 Answers1

1

You're probably looking for something like this:

Aes aes = Aes.Create();
aes.Key = yourByteArrayKey;
aes.IV = yourByteArrayIV;

// Save
using (FileStream fs = new FileStream(fileName, FileMode.Create)) {
    using (CryptoStream cs = new CryptoStream(fs, aes.CreateEncryptor(), CryptoStreamMode.Write)) {
        new BinaryFormatter().Serialize(cs, myObject);
    }
}

// Load
using (FileStream fs = new FileStream(fileName, FileMode.Open)) {
    using (CryptoStream cs = new CryptoStream(fs, aes.CreateEncryptor(), CryptoStreamMode.Read)) {
        myObject = (Templates)new BinaryFormatter().Deserialize(cs);
    }
}

You can use any other algorithm as long as it can return an ICrytoTransform, like the aes.CreateEncryptor() method (which is inherited from SymmetricAlgorithm)

Felype
  • 2,967
  • 2
  • 23
  • 35