Search code examples
c#serializationdeserializationbinaryformattercryptostream

Issue deserializing encrypted data using BinaryFormatter


Here is my code:

    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 and iv are both static byte arrays with a length of 8 which I'm using for testing purposes. There error is as follows:

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

Any help is much appreciated!


Solution

  • One small typo: your Load method should use des.CreateDecryptor, like this:

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