gpt4 book ai didi

c# - 使用 BinaryFormatter 反序列化加密数据

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

这是我的代码:

    public static void Save<T>(T toSerialize, string fileSpec) {
BinaryFormatter formatter = new BinaryFormatter();
DESCryptoServiceProvider des = new DESCryptoServiceProvider();

using (FileStream stream = File.Create(fileSpec)) {
using (CryptoStream cryptoStream = new CryptoStream(stream, des.CreateEncryptor(key, iv), CryptoStreamMode.Write)) {
formatter.Serialize(cryptoStream, toSerialize);
cryptoStream.FlushFinalBlock();
}
}
}

public static T Load<T>(string fileSpec) {
BinaryFormatter formatter = new BinaryFormatter();
DESCryptoServiceProvider des = new DESCryptoServiceProvider();

using (FileStream stream = File.OpenRead(fileSpec)) {
using (CryptoStream cryptoStream = new CryptoStream(stream, des.CreateEncryptor(key, iv), CryptoStreamMode.Read)) {
return (T)formatter.Deserialize(cryptoStream);
}
}
}

Key 和 iv 都是长度为 8 的静态字节数组,我将其用于测试目的。错误如下:

Binary stream '178' does not contain a valid BinaryHeader. Possible causes are invalid stream or object version change between serialization and deserialization

非常感谢任何帮助!

最佳答案

一个小错别字:您的Load 方法应该使用des.CreateDecryptor,如下所示:

public static T Load<T>(string fileSpec)
{
BinaryFormatter formatter = new BinaryFormatter();
DESCryptoServiceProvider des = new DESCryptoServiceProvider();

using (FileStream stream = File.OpenRead(fileSpec))
{
using (CryptoStream cryptoStream =
new CryptoStream(stream, des.CreateDecryptor(key, iv),
CryptoStreamMode.Read))
{
return (T)formatter.Deserialize(cryptoStream);
}
}
}

关于c# - 使用 BinaryFormatter 反序列化加密数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28893223/

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