title: Encrypt/Decrypt a serialized file
body: <p>Hey all I am trying to serialize a list of strings to a file, and then encrypt it.
  Currently its just not working.
  An unhandled exception of type 'System.Runtime.Serialization.SerializationException' occurred in mscorlib.dll</p>
  
  <p>Additional information: Binary stream '199' does not contain a valid BinaryHeader. Possible causes are invalid stream or object version change between serialization and deserialization.</p>
  
  <p>Then I need to decrypt and deseralize it. Heres what I have so far:</p>
  
  <p>Encrypting and seralizing: </p>
  
  <pre><code>public  void EncryptFile(FileInfo targetFile, string password, List&lt;string&gt; lines)
  {
      int SaltSize = 8;
      var keyGenerator = new Rfc2898DeriveBytes(password, SaltSize);
      var rijndael = Rijndael.Create();
  
      // BlockSize, KeySize in bit --&gt; divide by 8
      rijndael.IV = keyGenerator.GetBytes(rijndael.BlockSize / 8);
      rijndael.Key = keyGenerator.GetBytes(rijndael.KeySize / 8);
  
      using (var fileStream = targetFile.Create())
      {
          // write random salt
          fileStream.Write(keyGenerator.Salt, 0, SaltSize);
  
          using (var cryptoStream = new CryptoStream(fileStream, rijndael.CreateEncryptor(), CryptoStreamMode.Write))
          {
              var bformatter = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
  
              bformatter.Serialize(fileStream, lines);
  
  
          }
      }
  }
  </code></pre>
  
  <p>And un-seralizing and decrypting:</p>
  
  <pre><code>int SaltSize = 8;
  
  
  Dictionary&lt;string, string&gt; settings = new Dictionary&lt;string, string&gt;();
  
  
  
  var fileStream = File.Open(SettingsFile, FileMode.Open);
  var salt = new byte[SaltSize];
  fileStream.Read(salt, 0, SaltSize);
  
  // initialize algorithm with salt
  var keyGenerator = new Rfc2898DeriveBytes("Y8LwUKQVJkqRz2ZAKsAMtFWY", salt);
  var rijndael = Rijndael.Create();
  rijndael.IV = keyGenerator.GetBytes(rijndael.BlockSize / 8);
  rijndael.Key = keyGenerator.GetBytes(rijndael.KeySize / 8);
  
  // decrypt
  using (var cryptoStream = new CryptoStream(fileStream, rijndael.CreateDecryptor(), CryptoStreamMode.Read))
  {
      var bformatter = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
  
      List&lt;string&gt; settingsList = (List&lt;string&gt;)bformatter.Deserialize(cryptoStream);
      foreach (string setting in settingsList)
      {
          string[] bothWords = setting.Split(',');
          settings.Add(bothWords[0], bothWords[1]);
      }
  }
  </code></pre>