Encrypt password in App.config
95,140
Solution 1
Lets say this is your connection string:
<connectionStrings>
<add name="cs" connectionString="Data Source=myServerAddress;Initial Catalog=myDataBase;User Id=myUsername;Password=XXSDFASFDKSFJDKLJFDWERIODFSDFHSDJHKJNFJKSD;"/>
</connectionStrings>
Then you can do something like this:
string myCs = System.Configuration.ConfigurationManager.ConnectionStrings["cs"].ConnectionString;
System.Data.SqlClient.SqlConnectionStringBuilder csb = new System.Data.SqlClient.SqlConnectionStringBuilder(myCs);
csb.Password = EncDecHelper.Decrypt(csb.Password);
myCs = csb.ToString();
You can write EncDecHelper.Decrypt
by using samples from here: Encrypt and decrypt a string
Solution 2
Use the connectionStrings
configuration section and encrypt the whole section - instead of just the password.
This is safer as your app config will no longer have the server names and user names in plain text either.
There are how-to documents for encrypting configuration sections on MSDN for RSA or DPAPI.
Related videos on Youtube
Author by
NDeveloper
Updated on July 09, 2022Comments
-
NDeveloper almost 2 years
I want to encrypt the password in connection string. When I make a connection to DB the connection string is openly stored in App.config and I need to find a way to keep only password encrypted.
-
NDeveloper about 13 yearsBut as I understand anyone can decrypt it back ... Besides I want just encrypt password.
-
HABJAN about 13 years@NDeveloper: i changed my answer, take a look.
-
NDeveloper about 13 yearsThank you, this is exactly what I need.
-
One-One about 10 yearsIs there a way to make it work for an App.config file instead of just Web.config? Thanks for the answer though! +1
-
Oded about 10 years
-
erichste over 8 yearsI used the MySql version MySql.Data.MySqlClient.MySqlConnectionStringBuilder after seeing this post, worked great, thanks.
-
LatentDenis almost 7 years"This content is outdated and is no longer being maintained." Should it still be used? @Oded