I have a C# Windows Forms application. We are using nHibernate version 2.1 with Castle. We are installing our application in a secured vault. Therefore, we need to store the password in encrypted format in the hibernate.cfg.xml file. The C# code then decrypts the password. How can I set the nHibernate connectin string password to the decrypted string value in code?
Your best bet is probably to use Configuration.GetProperty
and Configuration.SetProperty
to modify the configuration defined in your hibernate.cfg.xml file:
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);
Where DecryptPasswordMatch
is defined as:
static string DecryptPasswordMatch(Match m)
{
string password = m.Groups[1].Value;
password = /* some method that decrypts password */;
return string.Format("Password={0}", password);
}
You'll have to change the regular expression slightly depending on your database engine (this should work for SQL Server).