C#nHibernate以编程方式设置数据库密码
我有一个C#Windows窗体应用程序。我们将nHibernate 2.1版与Castle一起使用。我们正在安全的vault中安装应用程序。因此,我们需要将密码以加密格式存储在hibernate.cfg.xml文件中。然后,C#代码对密码进行解密。如何将nHibernate connectin字符串密码设置为代码中已解密的字符串值?您最好使用C#nHibernate以编程方式设置数据库密码,c#,nhibernate,connection,set,programmatically-created,C#,Nhibernate,Connection,Set,Programmatically Created,我有一个C#Windows窗体应用程序。我们将nHibernate 2.1版与Castle一起使用。我们正在安全的vault中安装应用程序。因此,我们需要将密码以加密格式存储在hibernate.cfg.xml文件中。然后,C#代码对密码进行解密。如何将nHibernate connectin字符串密码设置为代码中已解密的字符串值?您最好使用Configuration.GetProperty和Configuration.SetProperty修改hibernate.cfg.xml文件中定义的配置
Configuration.GetProperty
和Configuration.SetProperty
修改hibernate.cfg.xml文件中定义的配置:
var configuration = new Configuration()
.Configure();
const string connectionStringKey = "connection.connection_string";
string connectionString = configuration.GetProperty(connectionStringKey);
connectionString = Regex.Replace(
connectionString,
"Password=(.+);",
DecryptPasswordMatch);
configuration.SetProperty(connectionStringKey, connectionString);
其中DecryptPasswordMatch
定义为:
static string DecryptPasswordMatch(Match m)
{
string password = m.Groups[1].Value;
password = /* some method that decrypts password */;
return string.Format("Password={0}", password);
}
您必须根据您的数据库引擎稍微更改正则表达式(这应该适用于SQL Server)。@MikeTWebb:当然可以,很高兴提供帮助。