c# - 使用 BinaryFormatter 反序列化加密数据时出现问题

标签 c# serialization deserialization binaryformatter cryptostream

这是我的代码:

    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/

相关文章:

c# - 如何创建与 TransactionScope 一起使用的类?

python-3.x - 类型错误 : can't pickle dict_items objects

c# - 如何反序列化具有依赖属性的 JSON?

java - 如何使用 Jackson 或任何其他 api 反序列化对象数组?

c# - VerticalLineAnnotation 未显示在 RangeBar MSChart 上

c# - 如何使用 API v3 .NET 删除 Google 日历中的事件?

c# - 使用自定义配置文件启动可执行文件

python - 如何在scrapy中使用项目字段对xml进行排序?

c++ - 在 C++ 中对某些序列化进行原型(prototype)化的快捷方式?

java - android应用程序中的序列化和反序列化