“Bad Data” Error – During Web.Config file Decryption
In one of my web application we are reading credentials from Web.config file’s Connection Strings section.
And we are encrypting the Connection Strings using aspnet_regiis.exe tool during deployments.
Below are the steps to Encrypt/Decryption of Config file using aspnet_regiis.exe tool
Encryption Command
- Open Visual Studio Command Prompt and run below commands.
Encrypt Connection Strings > aspnet_regiis.exe -pef “connectionStrings” “<Path of folder containing web.config file>”
Encrypt App Settings > aspnet_regiis.exe -pef “appSettings” “<Path of folder containing web.config file>”
- Ex: If my web.config exists at wwwroot folder, below is the command to encrypt ‘connectionStrings’ section
aspnet_regiis.exe -pef “connectionStrings” ” C:\inetpub\wwwroot\MyPublishedSite”
Decryption Command
Decrypt Connection Strings > aspnet_regiis.exe -pdf “connectionStrings” “<Path of folder containing web.config file>”
Decrypt App Settings > aspnet_regiis.exe -pdf “appSettings” “<Path of folder containing web.config file>”
How to read the encrypted values in your code?
- No need of any special statements in your code to the read the encrypted values.
- Your “ConfigurationManager” will take care (i.e., ConfigurationManager.AppSettings[“mypassword”] will return the actual value even if its encrypted)
Key points about Encryption/Decryption
- Encryption/Decryption is always specific to a machine.
- So you cannot decrypt a file on Machine 2 which has been encrypted on Machine 1 and ‘aspnet_regiis’ tool throws “Bad Data” error, if you attempt.
Reason and Fix for the “Bad Data” error:
- As mentioned earlier, Encryption/Decryption is always specific to a machine.
- In my case, I tried to Decrypt a file which was encrypted in my Test server, from my Local machine which resulted a “Bad Data” error.
- To fix the issue, I connected to “Test server” where the config file was originally encrypted, and decryption done successfully.
🙂