Reputation: 9090
I am trying to encrypt data that a serializable (xml) class contains. Here is a simple example:
[XmlRootAttribute("FooClass")]
public class FooClass
{
private string _personalData;
public PersonalData
{
set { _personalData = value;}
get { return _personalData; }
}
}
Assume there are ready to be used tho methods: Encrypt
& Decrypt
. Is there a way to use them somehow during the serialization in order to encrypt PersonalData
in the serialized output?
Upvotes: 3
Views: 1024
Reputation: 1963
Yes. You can use OnSerializingAttribute, OnDeserializingAttribute, and XmlIgnore attributes:
private string _encryptedPersonalData;
private string _personalData;
[XmlIgnore]
public PersonalData
{
set { _personalData = value;}
get { return _personalData; }
}
public string EncryptedPersonalData
{
get { return _encryptedPersonalData; }
set { _encryptedPersonalData = value; }
}
[OnDeserializingAttribute()]
internal void DecryptPersonalData(StreamingContext context)
{
// Decrypt data here
}
[OnSerializingAttribute()]
internal void EncryptPersonalData(StreamingContext context)
{
// Encrypt data here
}
Or something similar to this. These methods will be called before serialization occurs. More info: http://msdn.microsoft.com/en-US/library/ty01x675(v=VS.80).aspx
Upvotes: 3
Reputation: 44931
Yes. Mark PersonalData as nonserialized, then add a new property to return and accept the serialized data (note that the XmlAttribute is optional):
[XmlRootAttribute("FooClass")]
public class FooClass
{
private string _personalData;
[NonSerialized()]
public string PersonalData
{
set { _personalData = value;}
get { return _personalData; }
}
[XmlAttribute("PersonalData")]
public string PersonalDataEncrypted
{
set { _personalData = DecryptData(value);}
get { return EncryptData(_personalData); }
}
}
Upvotes: 4