2015-04-07 41 views
0

用例:以無人蔘與模式運行安裝程序。安全地存儲密碼並稍後檢索

如何: 要做到這一點,我使用的Process.Start並通過它的ProcessStartInfo如下:

var processStartInfo = new ProcessStartInfo 
{ 
     FileName = installerPath, 
     Arguments = commandLineArguments 
}; 

問題:在一個命令行參數的參數之一是用戶名密碼。用戶名和密碼由API提供。我正在做的是將加密的密碼保存在數據庫中,然後通過API返回。然後在接收端解密它。我知道它不是保存加密密碼的最佳做法(而應該保存密碼的散列),但請注意。請參閱上面提到的用例。

我想知道如果保存加密密碼(以後再解密)是最好的方法去這裏或有更好的方法。

+0

聽起來不像你有太多的選擇,只要你正確地加密它 - 這是最難的部分。另外請注意,任務管理器中可以看到命令行上的密碼。 – vcsjones

+0

@vcsjones是的。我知道密碼將在任務管理器中可見。我希望有一個SecureString的方式來做到這一點。 – souser

回答

1

對於加密我使用這個類:

/// <summary> 
/// Encrypt Password with local key 
/// </summary> 
public class SecureIt 
{ 
    #region Declaration 

    static byte[] entropy = System.Text.Encoding.Unicode.GetBytes("Salt Is Not A Password"); 

    #endregion 

    #region Methods 

    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; 
    } 

    #endregion 
} 

加密與本地計算機密鑰這樣做只能在同一臺機器可以解密密碼

安全字符串轉換爲不安全:

SecureIt.ToInsecureString(SecureIt.DecryptString(this._password)); 

轉換不安全的字符串安全:

SecureIt.EncryptString(SecureIt.ToSecureString(connection.Password)); 
+0

同一件東西不適合我。我可能會與這一個http://stackoverflow.com/questions/10168240/encrypting-decrypting-a-string-in-c-sharp/10177020#10177020 – souser