title: Using DataContractSerializer and DataProtectionProvider to serialize and encrypt an object
body: <p>I'm trying to serialize an object to a memory stream and then encrypt this stream and then write it to a file. Can't figure out what's wrong, the memory stream is empty after 'decryption'.</p>
  
  <pre><code>    public static async Task SerializeToFileEncrypt&lt;T&gt;(T o, StorageFile file)
      {
              DataContractSerializer dsc = new DataContractSerializer(typeof(T));                
              MemoryStream memoryStream = new MemoryStream();
              dsc.WriteObject(memoryStream, o);
              DataProtectionProvider provider = new DataProtectionProvider("Local=User");
              var raStream = await file.OpenAsync(FileAccessMode.ReadWrite);
              using(var filestream = raStream.GetOutputStreamAt(0))
              {
                  await provider.ProtectStreamAsync(memoryStream.AsInputStream(), filestream);
                  await filestream.FlushAsync();                        
              }
      }
  
      public static async Task&lt;T&gt; DeserializeFromFileDecrypt&lt;T&gt;(StorageFile file)
      {
          DataContractSerializer dsc = new DataContractSerializer(typeof(T));
          MemoryStream memoryStream = new MemoryStream();
          DataProtectionProvider provider = new DataProtectionProvider();
          await provider.UnprotectStreamAsync((await file.OpenStreamForReadAsync()).AsInputStream(), memoryStream.AsOutputStream());
          return (T) dsc.ReadObject(memoryStream);
      }
  </code></pre>