Reputation: 20803
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
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:
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
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