Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use OnSerializing and OnDeserializing attributes?

I have tried to implement auto encryption and decryption in my xml, but it doesn't just work, i.e. The data is not encrypted. What could be the reason? My code is shown below. I'm using the XmlSerializer class. Thanks

[Serializable]
public class User
{
    public string _username;
    public string _password;
    public string[] _roles;

    [XmlIgnore]
    public string Username
    {
        get { return _username; }
        set { _username = value; }
    }

    [XmlIgnore]
    public string Password
    {
        get { return _password; }
        set { _password = value; }
    }

    [XmlIgnore]
    public string[] Roles
    {
        get { return _roles; }
        set { _roles = value; }
    }

    [OnDeserializingAttribute]
    internal void DecryptPersonalData(StreamingContext context)
    {
        _username = Crypto.Decrypt(_username);
        _password = Crypto.Decrypt(_password);
        for (int i = 0; i < _roles.Length; i++)
        {
            _roles[i] = Crypto.Decrypt(_roles[i]);
        }
    }

    [OnSerializingAttribute]
    internal void EncryptPersonalData(StreamingContext context)
    {
        _username = Crypto.Encrypt(_username);
        _password = Crypto.Encrypt(_password);
        for (int i = 0; i < _roles.Length; i++)
        {
            _roles[i] = Crypto.Encrypt(_roles[i]);
        }
    }
}
like image 203
rtuner Avatar asked Jul 23 '13 09:07

rtuner


1 Answers

OnDeserializing isn't used by the XmlSerializer....to perform custom serialization with the XmlSerializer, derive from it, and handle the IXmlDeserializationCallback interface.

  • How do you find out when you've been loaded via XML Serialization?

Here is one suggested workaround (basically you would create a "Twin" class that returned encrypted data in it's gets, and did unecryption in its sets...you wouldn't only use the "Twin" during your serialization task...copy across from User into your User2).

  • http://codethatworks.wordpress.com/2009/11/15/xmlserializer-and-using-onserializing-ondeserialized-attributes/

Or you might be able to use the DataContractSerializer instead (but it is restrictive in that it doesn't support XML Attributes, only Elements in the serialized stream).

  • XML Serialisation - When To Use DataContractSerializer / Binary / XMLSerialiser
like image 99
CSmith Avatar answered Oct 23 '22 01:10

CSmith