Created
May 17, 2011 13:53
-
-
Save azyobuzin/976503 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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