So, there’s a lot of explanation about this, and it’s all quite confusing. Here’s a simple way I encrypted the web.config connection strings and how to use it from code.
I run the following snip in LINQPad (great tool…get it).
1 Configuration config = ConfigurationManager
2 .OpenMappedExeConfiguration(
3 new ExeConfigurationFileMap() {
4 ExeConfigFilename = @"c:\mywebsite\web.config"
5 },
6 ConfigurationUserLevel.None
7 );
8
9 config
10 .Sections["connectionStrings"]
11 .SectionInformation
12 .ProtectSection("DataProtectionConfigurationProvider");
13
14 config.Save();
In LINQPad, you will need to add a reference to System.Configuration.dll, and namespace imports for System.Configuration.
On line 12, you can use the Data Protection API provider (“DataProtectionConfigurationProvider”), or the RSA API Provider(“RSAProtectedConfigurationProvider”).
This makes your web.config a little messy:
<connectionStrings configProtectionProvider="DataProtectionConfigurationProvider">
<EncryptedData>
<CipherData>
<CipherValue>AQAAANCMnd8BFdERjHoAw…JG5PT1MoeB2hoxuO8=</CipherValue>
</CipherData>
</EncryptedData>
</connectionStrings>
But fortunately I don’t have to change connection strings often.
To access the encrypted connection strings from code, you don’t have to do anything different. That’s right: you don’t have to do anything different. Use your normal connection string code, and it will transparently retrieve your connection string.
To change your connection strings, you have to decrypt them, modify them, then re-encrypt them. Again, in LINQPad:
1 Configuration config = ConfigurationManager
2 .OpenMappedExeConfiguration(
3 new ExeConfigurationFileMap() {
4 ExeConfigFilename = @"c:\mywebsite\web.config"
5 },
6 ConfigurationUserLevel.None
7 );
8
9 config
10 .Sections["connectionStrings"]
11 .SectionInformation
12 .UnProtectSection();
13
14 config.Save();
You see that only line 12 changed. The provider used to protect the section is encoded in the cipher data, so you don’t need to provide one.
So, when your web site is ready to go live, run the above snippet and you will encrypt your connection string without any code modifications.
Update: 20 July 2007
You could also just do all of this via command line, and not have to worry about an exe or LINQPad.
To encrypt, aspnet_regiis –pef connectionStrings c:\mywebsite DataProtectionConfigurationProvider.
To decrpty, aspnet_regiis –pdf connectionStrings c:\mywebsite
d0adac99-3437-404b-80ff-98927a61aa0f|0|.0
Development
asp.net