gpt4 book ai didi

c# - 使用 DataContractSerializer 和 DataProtectionProvider 序列化和加密一个对象

转载 作者:行者123 更新时间:2023-11-30 22:29:26 27 4
gpt4 key购买 nike

我正在尝试将对象序列化为内存流,然后加密该流,然后将其写入文件。无法弄清楚哪里出了问题,'解密'后内存流为空。

    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);
}

最佳答案

完成写入后,您需要移动到 MemoryStream 的开头。否则没有什么可读的,因为你已经定位在最后。

这应该有效:

public static async Task SerializeToFileEncrypt<T>(T o, StorageFile file)
{
DataContractSerializer dsc = new DataContractSerializer(typeof(T));
MemoryStream memoryStream = new MemoryStream();
dsc.WriteObject(memoryStream, o);
memoryStream.Seek(0, SeekOrigin.Begin); // move to the beginning of the stream
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());
memoryStream.Seek(0, SeekOrigin.Begin); // move to the beginning of the stream
return (T) dsc.ReadObject(memoryStream);
}

关于c# - 使用 DataContractSerializer 和 DataProtectionProvider 序列化和加密一个对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10225174/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com