Encrypt Decrypt Web.config ConnectionString by Use aspnet_regiis

2015/10/312 min read
bookmark this
Responsive image

Encrypt connectionString

Following task is only for initial check-in for the encrypted connectionString, once you have checked-in the Encrypted connectionString you do not need to do following.

What following command is doing is, use aspnet_regiis.exe to encrypt connectionStrings from Web.config and use provider as customProvider


C:\Windows\Microsoft.NET\Framework\v4.0.30319>aspnet_regiis.exe -pef connectionStrings C:Projects2013\LDWebsite\Source\Development\DEV3\Website -prov "customProvider"  
C:\Windows\Microsoft.NET\Framework\v4.0.30319>aspnet_regiis.exe -pef connectionStrings {location where contains Web.config} -prov "customProvider"  
  <configProtectedData>
    <providers>
      <add name="customProvider"
           type="System.Configuration.RsaProtectedConfigurationProvider, System.Configuration, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" keyContainerName="myLDKey" useMachineContainer="true" />
    </providers>
  </configProtectedData>

Decrypt connectionString

copy the decrypt connectString to the Web.config's connectionString section and run following task. Then if will decrypt the connectionString. Following is check c driver's website folder's web.config.


C:\Windows\Microsoft.NET\Framework\v4.0.30319>aspnet_regiis.exe -pdf connectionStrings C:\Website -prov "customProvider"  
Share encrypt connectionString to other enviroment or web Farm
first need to export containerKey as xml by running following command
C:\Windows\Microsoft.NET\Framework\v4.0.30319>aspnet_regiis.exe -px "YourRSAKeyName" "c:\xmlKey.xml"  
At other environment just try to run following command
set "keyPath=%cd%\xmlKey.xml"  
cd C:\Windows\Microsoft.NET\Framework\v4.0.30319  
aspnet_regiis -pi "myKey" "%keyPath%"  
aspnet_regiis -pa "myKey" "NT AUTHORITY\NETWORK"  
pause

:: this task is for add RSA key so each machine so that encrpt connectionString could use at any enviroment, local, dev, qa or web farm.
:: webconfig's connectionString is already encrypted, if not running this task application would not be able to use encrypted connectionString.
:: following is pre requirement for running this task
:: 1. target machine is .NET 4.0
:: 2. under C:\Windows\Microsoft.NET\Framework\v4.0.30319, aspnet_regiis is exist
:: 3. website's application pool identity is running under NetworkService
:: If above 1-3 is valid, you're ready to run this command line.
:: First task is register RSA Key Container in side to the machine
:: Second task is grant networkService permission to the RSA Key Container
:: After run this two task if you see 'Succeeded!', then you're good!
:: about how to use aspnet_regiis.exe to encrypt webconfig see 

Complicated!!

I know, we could just use same service account for application pool and use that account to connet to database, so we could remove the user and password from connection string.