正則表達式匹配並替換字符串

場景:web

2012年在作廣州地鐵協同辦公項目時,客戶以爲明文的數據庫連接用戶密碼配置在web.config裏面不安全;其實.NET裏的web.config在IIS中有所限制,對安全性仍是有保障的。可是客戶既然有這樣稍微「變態」的需求,那咱們就考慮怎麼去把它實現吧。正則表達式

 

存在的技術難點:算法

(1)web.config中配置的數據庫連接用戶密碼必須是通過特殊加密的數據庫

(2)從第一點出發,既然要加密,那是選擇MD5之類的不可逆加密,仍是選擇AES256之類的可逆加密呢?因爲在數據訪問層中鏈接數據庫進行數據交互必須是有效的明文用戶和其密碼,因此咱們選擇AES256之類的可逆加密,加密解密算法能夠進一步自定義,這裏就不講解如何實現,相信online search下就不少相關文章了安全

 

好了,話很少說,代碼實踐見真理:ide

例如加密前爲: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 }
相關文章
相關標籤/搜索