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’.
public static async Task SerializeToFileEncrypt<T>(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<T> DeserializeFromFileDecrypt<T>(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);
}
You need to move to the beginning of
MemoryStreamonce you’re done writing to it. Otherwise there’s nothing to read from it since you’re already positioned at the end.This should work: