如何序列化在C#和prevent篡改的对象?对象、序列化、prevent

2023-09-03 23:27:18 作者:炼狱

我有一个C#类,如下所示:

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.

另外:

我会追加这个字符串作为查询字符串参数来一个网址。所以我想采取一些努力,以确保该字符串不能被轻易篡改。

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.

另外,我想序列化的方法是有效的,因此字符串的大小minmal。

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

具体的.NET Framework类/方法的任何建议,我应该使用?

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

推荐答案

1)要序列:

 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)prevent篡改:

2) To prevent tampering:

拿出一个秘密的字符串,例如MySecretWord。 把你的序列化对象实例作为一个字符串,并追加密语吧。 哈希的字符串(例如SHA的或使用HMAC(所建议的莱姆斯)的) 附加哈希的查询字符串 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

在接收端(也知道你的MySecretWord秘密字符串)你抛开散,取原序列化实例,追加已知的秘密字符串,并再次散列它。然后比较这两个哈希值是否相等。如果他们是平等的,你的字符串没有被修改。

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.

您可能需要地址/ Base64的恩code的字符串,因此它可以作为查询字符串。这也是很重要的,因为你需要查询字符串准确到达的发送。

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.