Neal Neal - 1 year ago 114
C# Question

Protecting a sensitive value (password) when using XML serialization?

We have a class that holds the user's logon profiles, it's a simple class that we just serialize to disk. We could certainly encrypt, compress, etc. etc. the serialization process, however, I want to keep it simple for other reasons.

One item that is serialized is the Password (string) property. I don't mind that it's being serialized but I want the value that is serialized to be 3DES encrypted so if someone were to open the file in some reader it wouldn't compromise the password. I know I can simply SET the password value as the encrypted value and GET the encrypted value but I want to automate it a little bit so that when the GET'er is called it handles the decryption, the SET'er handles the encryption so it's seamless.

What do you suggest is the best way to go about this? What I'm thinking is I need to mark the "Password" property to be ignored by the serializer and it's just a path to another property that holds the encrypted value and therefore returns it decrypted. Is this the best/only way to handle this? Just want to see if there is a simpler way before I go coding this up via the only way I can see doing this to keep the encryption/decryption within the serialized class logic.


Answer Source

You can mark the password property to be ignored by serialization and use kind of an wrapper property to be serialized:

public class LogonInfo
    public string Password { get; set; }

    public string EncPassword {
            return Encrypt(Password);
            Password = Decrypt(value);

    // TODO: add Encrypt and Decrypt methods
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download