2015-10-27 68 views
2

我有一個控制檯應用程序,我應該連接到SQL Server。它受密碼保護。如何在c#中的connectionStrings Web.config/App.config中只加密和解密密碼?

我要我曾嘗試這些方法從<connectionStrings>標籤僅解密密碼值一樣

<add name="ConnectionStringname" 
    connectionString="Data Source=xx.x.x.xx;Initial Catalog=DbName;User ID=xxx;Password="DecryptedValueOfPasword" /> 

,請讓我知道哪一個是最好的或任何其他方式請讓我知道。

方法1:加密和使用該命令

aspnet_regiis -pef connectionStrings "app.config Path" 

方法2解密整個<connectionStrings>標籤:加密和解密的唯一密碼值

  • 步驟1:刪除來自連接字符串的密碼值和自定義標記中添加的密碼值。

    <add name="ConnectionStringname" 
         connectionString="Data Source=xx.x.x.xx;Initial Catalog=DbName;User ID=xxx;" /> 
    
  • 步驟2:使用解密的RSA密鑰即使用aspnet_regiis.exe命令的自定義標籤。

  • 第3步:在代碼隱藏文件,讀取解密的密碼值,並在連接字符串添加密碼值

    <add name="ConnectionStringname" 
        connectionString="Data Source=xx.x.x.xx;Initial Catalog=DbName;User ID=xxx;Password="EncryptedValueOfPasword" /> 
    

方法3:創建類庫

public class EncryptDecryptClass { 
     public string Encrypt(string plainText) 
     { 
      if (plainText == null) 
       throw new ArgumentNullException("plainText"); 

      //encrypt data 
      var data = Encoding.Unicode.GetBytes(plainText); 
      byte[] encrypted = ProtectedData.Protect(data, null, Scope); 

      //return as base64 string 
      return Convert.ToBase64String(encrypted); 
     } 

     public string Decrypt(string cipher) 
     { 
      if (cipher == null) 
       throw new ArgumentNullException("cipher"); 

      //parse base64 string 
      byte[] data = Convert.FromBase64String(cipher); 

      //decrypt data 
      byte[] decrypted = ProtectedData.Unprotect(data, null, Scope); 
      return Encoding.Unicode.GetString(decrypted); 
     } 
    } 

回答

1

首先我不明白你爲什麼只能解密密碼值?連接字符串的其他部分表示安全信息,如數據庫名稱或用戶標識。所以你必須加密整個連接字符串,而不僅僅是它的一部分。

方法1是最好的選擇,因爲它具有以下優點:

  1. 你並不需要編寫加密/解密任何自定義代碼。
  2. 您不需要修改您的代碼,因爲.net框架會自動解密連接字符串。
  3. 管理員將能夠運行aspnet_regiis -pd "connectionStrings"
  4. 解密從服務器計算機中的連接字符串您可以在服務器之間import/export RSA key container如果你有一個服務器農場
+0

感謝ÿ我們的答案。 我只想解密密碼值。 使用第一種方法,如果我想解密app.config中的connectionStrings標籤,請在執行該命令後將app.config重命名爲web.config,然後將web.config重命名爲app.config。 – user17276

+0

是的,步驟是正確的。 –

0

使用XML配置,而不是你的file.store憑據在XML文件中的XML文件和加密的密碼,並從那裏

<?xml version="1.0" encoding="utf-8" ?> 
<Connections> 
    <UserId>sa</UserId> 
<Password>DecryptedValueOfPasword</Password> 
</Connectionstring> 

喜歡的東西上面