Tuesday, May 3, 2016

How to encrypt and decrypt configuration sections in app.config of window or console application with script

It is quite easy to encrypt web.config file in the web application. since Microsoft did provide us the tool (ASP.NET IIS Registration Tool (Aspnet_regiis.exe)) to get the job done.

you can simple run the following line in the CMD window to encrypt the connectionString sections in web.config file

I copied the below command line from MSDN Encrypting and Decrypting Configuration Sections
 
aspnet_regiis -pe "connectionStrings" -app "/SampleApplication" 
-prov "RsaProtectedConfigurationProvider"

the above commend line with encrypt the connection string section with RsaProtectedConfigurationProvider.

However the configuration file of window or console application is app.config. ASP.Net IIS Registration Tool will not work in this case. However there is  work around. we can simply rename the app.config to web.config file, then run the encrypt command. Finally we rename web.config file back to app.config.

 Script encrypt the app.config file


copy App.Config App.Config.Encrpytoriginal
rename App.config web.config
C:\Windows\Microsoft.NET\Framework64\v4.0.30319\aspnet_regiis -pef connectionStrings . -prov DataProtectionConfigurationProvider
C:\Windows\Microsoft.NET\Framework64\v4.0.30319\aspnet_regiis -pef appSettings . -prov DataProtectionConfigurationProvider
rename web.config App.config

Script to decrypt the app.config file

del App.Config.Decryptoriginal
copy App.Config App.Config.Decryptoriginal
rename App.config web.config
C:\Windows\Microsoft.NET\Framework64\v4.0.30319\aspnet_regiis -pdf connectionStrings . 
C:\Windows\Microsoft.NET\Framework64\v4.0.30319\aspnet_regiis -pdf appSettings . 
rename web.config App.config

you can save those scripts into two different batch files, and place them in your app project folder.

as a result, you can encrypt and decrypt in your configration section in the fly.


No comments:

Post a Comment