How to encrypt my connection string ?

i am using c# windows application. I am maintaining connection string information in machine.config file. How to encrypt my connection string in machine.config file and how to decrypt during accessing the application ?
Varshini SAsked:
Who is Participating?
Éric MoreauConnect With a Mentor Senior .Net ConsultantCommented:
SammyConnect With a Mentor Commented:
You can encrypt and de-crypt any config file by using the DataProtectionConfigurationProvider
see the demo here

just a side note, you shouldn't encrypt the machine.config, you should use an app.confg in your application and encrypt it. the machine.config is a machine level configuration file and should not be touched by a single app.
käµfm³d 👽Commented:
I concur with the above. Take advantage of IIS's ability to cascade configuration files. Place--if not already there--a top-level config file in your IIS application directory, and then put your connection strings there. You should rarely ever need to edit machine.config.
Keep up with what's happening at Experts Exchange!

Sign up to receive Decoded, a new monthly digest with product updates, feature release info, continuing education opportunities, and more.

Varshini SAuthor Commented:
kaufmed - It is the windows application.
Varshini SAuthor Commented:
Sammy: i have used the sample application but when i use the encrypted values in my app.config file in the run time it is showing exception

An unhandled exception of type 'System.NullReferenceException' occurred in WindowsFormsApplication1.exe
Varshini SAuthor Commented:

My app.config file
<?xml version="1.0" encoding="utf-8" ?>
<configuration  xmlns="">
        <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5" />

       <add name="DB2" connectionString="Data Source=SSA1\SQLEXPRESS2012;
    Initial Catalog=SAMPLE1;User ID=sa;Password=****" />



Open in new window

Encrypted key:

<?xml version="1.0" encoding="utf-8"?>
    <connectionStrings configProtectionProvider="DataProtectionConfigurationProvider">

Open in new window

Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.