ASP.NET How Encrypt Connection Strings Section in Web.Config File

This post describe how to encrypt a connection string in your configuration file (web.config).

To Encrypt your web.config file you can use a tool called 'aspnet_regiis.exe' under your folder C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727.
what you have to do:
1. Open command line (Click run then type 'cmd')
2. Go to folder C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727.
3. type this command:
        aspnet_regiis.exe -pef "connectionStrings" C:/MyWeb (if your application type is a file system)  OR
        aspnet_regiis.exe -pe "connectionStrings" -app /MyWeb (if an IIS aplication)

this is an example

Before encrypted:
<connectionStrings>
<add name="MyLocalSQLServer"
connectionString="Initial Catalog=mydatabase;
data source=localhost;Integrated Security=SSPI;"
providerName="System.Data.SqlClient"/>
</connectionStrings>

After encrypted:

<connectionStrings configProtectionProvider="DataProtectionConfigurationProvider">
<EncryptedData>
<CipherData>
<CipherValue>AQAAANCMnd8BFdERjHoAwE/Cl+sBAAAAexuIJ/8oFE+sGTs7jBKZdgQAAAACAAAAAAADZgAAqAAAABAAAAA
Kms84dyaCPAeaSC1dIMIBAAAAAASAAACgAAAAEAAAAKaVI6aAOFdqhdc6w1Er3HMwAAAAcZ00MZOz1dI7kYRvkMIn/
BmfrvoHNUwz6H9rcxJ6Ow41E3hwHLbh79IUWiiNp0VqFAAAAF2sXCdb3fcKkgnagkHkILqteTXh</CipherValue>
</CipherData>
</EncryptedData>
</connectionStrings>

Why should i encrypt the web.config?
you should encrypt the information on your configuration files, because this files contains critical informations such as your connection strings which has a readable username and password of your database.

Then, after the information encrypted, should i decrypt it if i wanna call the information on my code?
No, you no need to decrypt the information, it will automatically decrypt.
So whenever you called the configuration using

ConfigurationManager.ConnectionStrings["MyConnStrName"]
it will return decrypted text of your connection string. so you don't have to worried about decrypting this information
.

After i encrypt the web.config, I need to edit my connection string, how can i do?
you can decrypt to readable text by using this command:
aspnet_regiis.exe -pdf "connectionStrings" C:/MyWeb (if your application type is a file system)  OR
aspnet_regiis.exe -pd "connectionStrings" -app /MyWeb (if an IIS aplication)


_Chris_






Next Recommended Reading Encode query string in asp.net