2012-01-06 56 views

回答

7
+0

密码tnkx很多的帮助和链接功能 – 2012-01-06 15:34:00

3

你可以逮捕(的DbContext或IdentityDbContext如果使用ASPNET标识)从上下文类连接字符串调用和修改连接字符串返回。在我的情况下,我不是加密整个连接字符串,而是选择只加密密码。您可以使用相同的方法来加密整个连接字符串。

注:此功能(StringCipher.Decrypt)用于加密和解密来自这个话题 - >https://stackoverflow.com/a/1344255/1390025

在这里你抓的呼叫连接字符串

 public YourDB() 
     : base(GetSqlConnection("DefaultConnection")) 
    {} 

在上面场景我从app.config或web.config获取连接字符串。但是,根据您的请求,您可以加密整个连接字符串并像下面的示例一样;

public YourDB() 
     : base(StringCipher.Decrypt("your-encrypted-connection-string", "passphrase-used-to-encrypt")) 
    {} 

在仅该密码被加密的情况下,该功能下面替换纯文本加密的密码,并返回连接字符串;

 public static string GetSqlConnection(string connectionStringName = "DefaultConnection") 
    { 
     // optionally defaults to "DefaultConnection" if no connection string name is inputted 
     string connectionString = ConfigurationManager.ConnectionStrings[connectionStringName].ConnectionString; 
     string passPhrase = "passphrase-used-to-encrypt"; 
     // decrypt password 
     string password = get_prase_after_word(connectionString, "password=", ";"); 
     connectionString = connectionString.Replace(password, StringCipher.Decrypt(password, passPhrase)); 
     return connectionString; 
    } 

用来解析从连接字符串

 public static string get_prase_after_word(string search_string_in, string word_before_in, string word_after_in) 
    { 
     int myStartPos = 0; 
     string myWorkString = ""; 

     // get position where phrase "word_before_in" ends 

     if (!string.IsNullOrEmpty(word_before_in)) 
     { 
      myStartPos = search_string_in.ToLower().IndexOf(word_before_in) + word_before_in.Length; 

      // extract remaining text 
      myWorkString = search_string_in.Substring(myStartPos, search_string_in.Length - myStartPos).Trim(); 

      if (!string.IsNullOrEmpty(word_after_in)) 
      { 
       // get position where phrase starts in the working string 
       myWorkString = myWorkString.Substring(0, myWorkString.IndexOf(word_after_in)).Trim(); 

      } 
     } 
     else 
     { 
      myWorkString = string.Empty; 
     } 
     return myWorkString.Trim(); 
    }