場景:
2012年在做廣州地鐵協同辦公項目時,客戶覺得明文的數據庫鏈接用戶密碼配置在web.config里面不安全;其實.NET里的web.config在IIS中有所限制,對安全性還是有保障的。但是客戶既然有這樣稍微“變態”的需求,那我們就考慮怎么去把它實現吧。
存在的技術難點:
(1)web.config中配置的數據庫鏈接用戶密碼必須是經過特殊加密的
(2)從第一點出發,既然要加密,那是選擇MD5之類的不可逆加密,還是選擇AES256之類的可逆加密呢?由於在數據訪問層中連接數據庫進行數據交互必須是有效的明文用戶和其密碼,所以我們選擇AES256之類的可逆加密,加密解密算法可以進一步自定義,這里就不講解如何實現,相信online search下就很多相關文章了
好了,話不多說,代碼實踐見真理:
例如加密前為:eip_hr_user123,加密后為:3OHOG6W9NgpJTriw4x6JDg==
dataconfiguration.config配置文件內容:
1 <configuration> 2 <configSections> 3 <section name="dataConfiguration" type="Microsoft.Practices.EnterpriseLibrary.Data.Configuration.DatabaseSettings, Microsoft.Practices.EnterpriseLibrary.Data, Version=3.1.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" /> 4 </configSections> 5 <dataConfiguration defaultDatabase="ORADBConnection" /> 6 <connectionStrings> 7 <add name="ORADBConnection" connectionString="Persist Security Info=True;User ID=eip_hr_user;Password=3OHOG6W9NgpJTriw4x6JDg==;Data Source=prd" 8 providerName="System.Data.OracleClient" /> 9 </connectionStrings> 10 </configuration>
.NET中使用正則表達式匹配並替換字符串,其實在JavaScript中也可以用這樣的正則表達式,只是寫法大同小異而已:
1 internal Database oraDB 2 { 3 get 4 { 5 if (_oradb != null) return _oradb; 6 FileConfigurationSource dataSource = new FileConfigurationSource("dataconfiguration.config"); 7 ConnectionStringsSection csSection = (ConnectionStringsSection)dataSource.GetSection("connectionStrings"); 8 ConnectionStringSettings csSettings = csSection.ConnectionStrings["ORADBConnection"]; 9 if (csSettings != null) 10 { 11 string connectionStr = csSettings.ConnectionString; 12 //author: Kenmu 13 //created time: 2012-09-24 14 //function: 針對密碼進行加密的情況,必須解密 begin 15 string pwd; 16 Regex r = new Regex("Password=(?<Pwd>[^;]+)", RegexOptions.IgnoreCase);//?<Pwd>為標示符,不參與匹配的;+?表示非貪婪匹配 17 Match m = r.Match(connectionStr); 18 if (m.Success) 19 { 20 pwd = m.Groups["Pwd"].Value; //獲取到密文 21 try 22 { 23 connectionStr = connectionStr.Replace(string.Format("={0}", pwd), string.Format("={0}", Cryptogram.DecryptPassword(pwd))); //對密文進行解密操作,Cryptogram.DecryptPassword為自定義的可逆解密方法 24 } 25 catch 26 { 27 } 28 } 29 //function: 針對密碼進行加密的情況,必須解密 end 30 _oradb = new OracleDatabase(connectionStr); 31 } 32 return _oradb; 33 } 34 }