I am writing a small xml config file that will be saved and loaded from a specific location (so no using user.config
). My application is .NET 2.0 and can not be moved to a newer version (so no DataContractSerializer
) I am required to implement a "Save Password" option so the password field will be pre-filled in when the user uses the app.
Currently here is how I do it
public class UserSettings
{
//Snip many other properties...
public bool SavePassword { get; set; }
[XmlIgnore]
public string Password
{
get
{
string retVal = string.Empty;
if (ProtectedPassword != null)
{
try
{
retVal = Encoding.UTF8.GetString(ProtectedData.Unprotect(ProtectedPassword, _md5.ComputeHash(Encoding.UTF8.GetBytes(this.Username.ToUpper())), DataProtectionScope.LocalMachine));
}
catch
{
retVal = string.Empty;
}
}
return retVal;
}
set
{
ProtectedPassword = ProtectedData.Protect(Encoding.UTF8.GetBytes(value), _md5.ComputeHash(Encoding.UTF8.GetBytes(this.Username.ToUpper())), DataProtectionScope.LocalMachine);
}
}
public byte[] ProtectedPassword;
private readonly MD5 _md5 = MD5.Create();
public void Save()
{
var xOver = new XmlAttributeOverrides();
//If Save password is false do not store the encrypted password
if (this.SavePassword == false)
{
var xAttrs = new XmlAttributes();
xAttrs.XmlIgnore = true;
xOver.Add(typeof(UserSettings), "ProtectedPassword", xAttrs);
}
XmlSerializer xSer = new XmlSerializer(typeof(UserSettings), xOver);
Directory.CreateDirectory(Path.GetDirectoryName(savePath));
using(var fs = new FileStream(savePath, FileMode.Create))
{
xSer.Serialize(fs, this);
}
}
I would like to make ProtectedPassword
not public however if I set it to anything other than public xSer.Serialize(fs, this)
will not include the property. What do I need to do to make this work correctly?
I know there are many other similar questions to this, however none of them have the .NET 2.0 requirement and use solutions that are not available to a person who is limited to 2.0. Is there any option other than writing a custom XMLSerarlizer
or living with the fact that ProtectedPassword
is public.