Thursday, March 7, 2013

Simple way to save Password in a settings file.

 /// <summary>
 /// Description of Settings.
 /// </summary>
 public class Settings:ApplicationSettingsBase
 {
  private static Settings defaultInstance = ((Settings)(ApplicationSettingsBase.Synchronized(new Settings())));
  
  public static Settings Default {
   get {
    return defaultInstance;
   }
  }
  
  public Settings():base()
  {
  }
  
  [UserScopedSettingAttribute()]
  [DefaultSettingValueAttribute("false")]
  public bool PASS_SET {
   get { return (bool)this["PASS_SET"]; }
   private set { this["PASS_SET"] = value; }
  }
  
  [UserScopedSettingAttribute()]
  [DefaultSettingValueAttribute("")]
  /// <summary>
  /// <returns> null if !PASS_SET</returns>
  /// </summary>
  public string Password {
   get {
    return (PASS_SET)?ToInsecureString(DecryptString(this["Password"].ToString())):null;}
   set { this["Password"] = EncryptString(ToSecureString(value)); PASS_SET=true; }
  }
  static byte[] entropy = System.Text.Encoding.Unicode.GetBytes("Bumblebee Tuna, I can see your balls!");

  public static string EncryptString(System.Security.SecureString input)
  {
   byte[] encryptedData = System.Security.Cryptography.ProtectedData.Protect(
    System.Text.Encoding.Unicode.GetBytes(ToInsecureString(input)),
    entropy,
    System.Security.Cryptography.DataProtectionScope.CurrentUser);
   return Convert.ToBase64String(encryptedData);
  }

  public static SecureString DecryptString(string encryptedData)
  {
   try
   {
    byte[] decryptedData = System.Security.Cryptography.ProtectedData.Unprotect(
     Convert.FromBase64String(encryptedData),
     entropy,
     System.Security.Cryptography.DataProtectionScope.CurrentUser);
    return ToSecureString(System.Text.Encoding.Unicode.GetString(decryptedData));
   }
   catch
   {
    return new SecureString();
   }
  }

  public static SecureString ToSecureString(string input)
  {
   SecureString secure = new SecureString();
   foreach (char c in input)
   {
    secure.AppendChar(c);
   }
   secure.MakeReadOnly();
   return secure;
  }

  public static string ToInsecureString(SecureString input)
  {
   string returnValue = string.Empty;
   IntPtr ptr = System.Runtime.InteropServices.Marshal.SecureStringToBSTR(input);
   try
   {
    returnValue = System.Runtime.InteropServices.Marshal.PtrToStringBSTR(ptr);
   }
   finally
   {
    System.Runtime.InteropServices.Marshal.ZeroFreeBSTR(ptr);
   }
   return returnValue;
  }
 }

No comments:

Post a Comment