frankadelic
frankadelic

Reputation: 20803

How to serialize an object in C# and prevent tampering?

I have a C# class as follows:

public class TestObj
{
    private int intval;
    private string stringval;
    private int[] intarray;
    private string[] stringarray;

    //... public properties not shown here
}

I would like to serialize an instance of this class into a string.

In addition:

I will be appending this string as a QueryString param to a URL. So I would like to take some effort to ensure that the string cannot be tampered with easily.

Also, I would like the serialization method to be efficient so the size of the string is minmal.

Any suggestions of specific .NET Framework classes/methods I should use?

Upvotes: 3

Views: 2005

Answers (2)

Alex
Alex

Reputation: 77329

1) To serialize:

 public String SerializeObject(TestObj object)
 {
        String Serialized = String.Empty;
        MemoryStream memoryStream = new MemoryStream ( );
        XmlSerializer xs = new XmlSerializer(typeof(TestObj));
        XmlTextWriter xmlTextWriter = new XmlTextWriter ( memoryStream, Encoding.UTF8 );
        xs.Serialize (xmlTextWriter, object);
        memoryStream = (MemoryStream) xmlTextWriter.BaseStream;
        Serialized = UTF8Encoding.GetString(memoryStream.ToArray());
        return Serialized;
 }

2) To prevent tampering:

  • Come up with a secret string, e.g. "MySecretWord".
  • Take your serialized object instance as a string, and append the secret word to it.
  • Hash the string (e.g. SHA or use HMAC (as suggested by Remus) )
  • Append the hash to the query string

On the receiving side (which also knows your "MySecretWord" secret string) you strip away the hash, take the original serialized instance, append the known secret string and hash it again. Then compare the two hashes for equality. If they are equal, your string was not modified.

You may need to Url/Base64 Encode your string so it works as a query string. This is also important as you need the query string to arrive exactly as sent.

Upvotes: 4

Remus Rusanu
Remus Rusanu

Reputation: 294317

Sign the stream and add the signature to your query. Use a HMAC signing algorithm, like HMACSHA1. You will need to have a secret between your client and your server to sign and validate the signature.

Upvotes: 4

Related Questions