Skip to content

Instantly share code, notes, and snippets.

@azyobuzin
Created May 17, 2011 13:53
Show Gist options
  • Save azyobuzin/976503 to your computer and use it in GitHub Desktop.
Save azyobuzin/976503 to your computer and use it in GitHub Desktop.
using System;
using System.IO;
using System.Reflection;
using System.Security.Cryptography;
using System.Text;
using System.Xml.Serialization;
using Livet;
namespace Azyobuzi.HatenaDiaryClient.Models
{
public class Settings : NotifyObject, ICloneable
{
private static readonly byte[] entropy = Encoding.UTF32.GetBytes("futonmofumofufutonmofumofu");
private static readonly string settingsFile =
Path.GetDirectoryName(Environment.GetCommandLineArgs()[0]) + @"\settings.xml";
private Settings() { }
string _HatenaId;
[XmlIgnore]
public string HatenaId
{
get
{ return _HatenaId; }
set
{
if (_HatenaId == value)
return;
_HatenaId = value;
RaisePropertyChanged("HatenaId");
}
}
string _Password;
[XmlIgnore]
public string Password
{
get
{ return _Password; }
set
{
if (_Password == value)
return;
_Password = value;
RaisePropertyChanged("Password");
}
}
public string EncryptedIdPassword { set; get; }
private void Encrypt()
{
EncryptedIdPassword = Encoding.UTF32.GetString(
ProtectedData.Protect(
Encoding.UTF32.GetBytes(string.Join(":", this.HatenaId, this.Password)),
entropy,
DataProtectionScope.LocalMachine
));
}
private void Decrypt()
{
var idPass = Encoding.UTF32.GetString(
ProtectedData.Unprotect(
Encoding.UTF32.GetBytes(this.EncryptedIdPassword),
entropy,
DataProtectionScope.LocalMachine
))
.Split(':');
this.HatenaId = idPass[0];
this.Password = idPass[1];
}
public static Settings Load()
{
try
{
using (var sr = new StreamReader(settingsFile, Encoding.UTF32))
{
var xs = new XmlSerializer(typeof(Settings));
var re = (Settings)xs.Deserialize(sr);
re.Decrypt();
return re;
}
}
catch
{
return new Settings();
}
}
public void Save()
{
this.Encrypt();
using (var sw = new StreamWriter(settingsFile, false, Encoding.UTF32))
{
var xs = new XmlSerializer(typeof(Settings));
xs.Serialize(sw, this);
}
}
public object Clone()
{
this.Save();
return Load();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment