您的位置:首页 > 其它

正则表达式匹配并替换字符串

2015-05-29 23:54 267 查看
场景:

2012年在做广州地铁协同办公项目时,客户觉得明文的数据库链接用户密码配置在web.config里面不安全;其实.NET里的web.config在IIS中有所限制,对安全性还是有保障的。但是客户既然有这样稍微“变态”的需求,那我们就考虑怎么去把它实现吧。

存在的技术难点:

(1)web.config中配置的数据库链接用户密码必须是经过特殊加密的

(2)从第一点出发,既然要加密,那是选择MD5之类的不可逆加密,还是选择AES256之类的可逆加密呢?由于在数据访问层中连接数据库进行数据交互必须是有效的明文用户和其密码,所以我们选择AES256之类的可逆加密,加密解密算法可以进一步自定义,这里就不讲解如何实现,相信online search下就很多相关文章了

好了,话不多说,代码实践见真理:

例如加密前为:eip_hr_user123,加密后为:3OHOG6W9NgpJTriw4x6JDg==
dataconfiguration.config配置文件内容:

<configuration>
<configSections>
<section name="dataConfiguration" type="Microsoft.Practices.EnterpriseLibrary.Data.Configuration.DatabaseSettings, Microsoft.Practices.EnterpriseLibrary.Data, Version=3.1.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
</configSections>
<dataConfiguration defaultDatabase="ORADBConnection" />
<connectionStrings>
<add name="ORADBConnection" connectionString="Persist Security Info=True;User ID=eip_hr_user;Password=3OHOG6W9NgpJTriw4x6JDg==;Data Source=prd"
providerName="System.Data.OracleClient" />
</connectionStrings>
</configuration>


.NET中使用正则表达式匹配并替换字符串,其实在JavaScript中也可以用这样的正则表达式,只是写法大同小异而已:

internal Database oraDB
{
get
{
if (_oradb != null) return _oradb;
FileConfigurationSource dataSource = new FileConfigurationSource("dataconfiguration.config");
ConnectionStringsSection csSection = (ConnectionStringsSection)dataSource.GetSection("connectionStrings");
ConnectionStringSettings csSettings = csSection.ConnectionStrings["ORADBConnection"];
if (csSettings != null)
{
string connectionStr = csSettings.ConnectionString;
//author: Kenmu
//created time: 2012-09-24
//function: 针对密码进行加密的情况,必须解密 begin
string pwd;
Regex r = new Regex("Password=(?<Pwd>[^;]+)", RegexOptions.IgnoreCase);//?<Pwd>为标示符,不参与匹配的;+?表示非贪婪匹配
Match m = r.Match(connectionStr);
if (m.Success)
{
pwd = m.Groups["Pwd"].Value; //获取到密文
try
{
connectionStr = connectionStr.Replace(string.Format("={0}", pwd), string.Format("={0}", Cryptogram.DecryptPassword(pwd))); //对密文进行解密操作,Cryptogram.DecryptPassword为自定义的可逆解密方法
}
catch
{
}
}
//function: 针对密码进行加密的情况,必须解密 end
_oradb = new OracleDatabase(connectionStr);
}
return _oradb;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: