How to encrypt decrypt connection string in webconfig file?

How to Secure Connection Strings, Encrypt Connection String

ASP.NET gives a built in way to do this. We can use RSAProtectedConfigurationProvider to encrypt the connection strings using User Level Key and Machine Level Key. User Level Key is used when you are running your application on a shared server and Machine Level Key is used when you are running your application on dedicated server.

DataProtectionConfgurationProvider (Machine Level Key)

This provider uses windows data protection application programming interface to encrypt and decrypt the data. The encrypting and decrypting of connection strings in web.config file will do by using aspnet_regiis.exe command line tool and code behind.

RSAProtectedConfigurationProvider (User Level Key): 

This is default provider and uses the RSA public key encryption algorithm to encrypt and decrypt data.

Method 1st:
First we will do encryption and decryption using aspnet_regiis.exe command line tool in file system website
First we add a sample connection string in web.config file such as:

    <add name="myconstr" connectionString="Driver={MySQL ODBC 3.51 Driver};SERVER=localhost; DATABASE=demo;Port=3306;USER=root;PASSWORD=;Connect Timeout=0;" />

After open command prompt type the following command:

There write this command on command prompt:

aspnet_regiis -pef "connectionStrings" "C:\Users\lepton\Desktop\Encrypt_Decrypt_constring"

Note: Here the "C:\Users\lepton\Desktop\Encrypt_Decrypt_constring" is the physical path of your website and pef indicates that the application is built as File System website. Review the web.config after this. You will find it encrypted.

Now open your application and check connectionStrings in web.config file that would be like this:
<connectionStrings configProtectionProvider="RsaProtectedConfigurationProvider">
    <EncryptedData Type="" xmlns="">
      <EncryptionMethod Algorithm="" />
      <KeyInfo xmlns="">
        <EncryptedKey xmlns="">
          <EncryptionMethod Algorithm="" />
          <KeyInfo xmlns="">
            <KeyName>Rsa Key</KeyName>

Later on you can access this connection string as normal way in your pages:

- To revert the web.config connection strings back to plain text:
aspnet_regiis -pdf "connectionStrings" "C:\Users\lepton\Desktop\Encrypt_Decrypt_constring"

Now check your connctionStrings section in your web.config file you will see decrypted connection string.
All Rights Reserved by Etechpulse © 2015 - 2016
Powered By Blogger

Contact Form


Email *

Message *

Powered by Blogger.