Adam Heeg
Adam Heeg

Reputation: 1714

Is there any issue with encrypting and encoding serialized data?

Here is my code, I get this error when deserializing it. I'm testing it in the same call, so versioning of .net shouldn't be an issue. My user data is a basic poco object.

Step 1, Serialize and encrypt:

    byte[] userDataArray;
    BinaryFormatter bf = new BinaryFormatter();
    using (MemoryStream ms = new MemoryStream())
    {
        bf.Serialize(ms, _logicLibrary.userData);
        userDataArray = ms.ToArray();
    }

    string data = Encoding.UTF8.GetString(userDataArray);

    var encrytedUserData = logic.Encrypt(data);

    return Encoding.UTF8.GetBytes(encrytedUserData);

Step 2 decrypt and deserialize:

    public UserData DeserializeUserData(string data)
    {
        string decryptedSerializedData = _logicLibrary.RunDecrypt(data);

        var dataBytes = Encoding.UTF8.GetBytes(decryptedSerializedData);

        BinaryFormatter bf = new BinaryFormatter();
        using (MemoryStream ms = new MemoryStream(dataBytes))
        {
            return bf.Deserialize(ms) as UserData;
        }

    }

My error when deserializing is this:

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

Upvotes: 0

Views: 372

Answers (2)

Adam Heeg
Adam Heeg

Reputation: 1714

Based on the good suggestions here I reworked my encryption methods to accept input and outputs of type byte[]. After that I made sure that any data that was not a string never touched a Encoding.UTF8 based on lots of stuff including the following post. These tips combined to make my code work. UserData is a custom class.

private UserData DeserializeUserData(byte[] data)
{
    byte[] decryptedSerializedData = logic.Decrypt(data);


    BinaryFormatter bf = new BinaryFormatter();
    using (MemoryStream ms = new MemoryStream(decryptedSerializedData))
    {
        return bf.Deserialize(ms) as UserData;
    }

}

private byte[] SerializeUserData(UserData userData)
{
    byte[] userDataArray;
    BinaryFormatter bf = new BinaryFormatter();
    using (MemoryStream ms = new MemoryStream())
    {
        bf.Serialize(ms, userData);
        userDataArray = ms.ToArray();
    }

    return logic.Encrypt(userDataArray);

}

Upvotes: 0

John Boker
John Boker

Reputation: 83709

You can probably do something like

Convert.ToBase64String(arrayOfData);
Convert.FromBase64String(stringBase64Encoded);

to get a string and convert it back to a byte array.

https://msdn.microsoft.com/en-us/library/dhx0d524(v=vs.110).aspx

https://msdn.microsoft.com/en-us/library/system.convert.frombase64string(v=vs.110).aspx

Upvotes: 1

Related Questions