【问题标题】:Issue deserializing encrypted data using BinaryFormatter使用 BinaryFormatter 对加密数据进行反序列化问题
【发布时间】:2015-05-07 17:30:45
【问题描述】:

这是我的代码:

    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 的静态字节数组,我将其用于测试目的。错误如下:

二进制流“178”不包含有效的 BinaryHeader。可能的原因是无效的流或序列化和反序列化之间的对象版本更改

非常感谢任何帮助!

【问题讨论】:

  • 在调用 save 和调用 load 之间,您是否更新了窗口或修改了项目中的任何其他 DLL?
  • @ScottChamberlain 是的,有没有另一种方法来做我正在做的事情而不考虑这个?我会定期更新我的应用程序。
  • 不应该Load 使用CreateDecryptor,而不是CreateEncryptor
  • BinaryFormater 不容忍版本更改,你完蛋了。您不应该保留由 BinaryFormatter 序列化的数据,您需要使用 XMLSeralizer 或像 ProtoBuf 这样的第 3 方二进制格式。 BinaryFormatter 仅用于 IPC 通信。
  • "您需要使用 XMLSeralizer 或像 ProtoBuf 这样的第 3 方二进制格式。BinaryFormatter 仅用于 IPC 通信。"

标签: c# serialization deserialization binaryformatter cryptostream


【解决方案1】:

一个小错字:你的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);
        }
    }
}

【讨论】:

  • 我不敢相信我做到了 xD
猜你喜欢
  • 1970-01-01
  • 2014-12-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多