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

余生长醉 提交于 2019-12-22 09:24:30

问题


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?


回答1:


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.




回答2:


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.



来源:https://stackoverflow.com/questions/1331081/how-to-serialize-an-object-in-c-sharp-and-prevent-tampering

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!