使用 BinaryFormatter 反序列化加密数据

Issue deserializing encrypted data using BinaryFormatter

这是我的代码:

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