Introduction:
In this article,i am going to explain about how to encrypt and decrypt web.config entries using asp.net.
Main:
We can encrypt and decrypt web.config entries in the following two ways,
1.WebConfiguration Class,
Using System.Web.Configuration;
For Encryption AppSettings,
Configuration local_config = WebConfigurationManager.OpenWebConfiguration(HttpContext.Current.Request.ApplicationPath);
ConfigurationSection local_section = config.GetSection(appSettings);
if (!local_section.SectionInformation.IsProtected)
{
if (!local_section.ElementInformation.IsLocked)
{
string local_encMethod = encryptionProvider.ToString();
local_section.SectionInformation.ProtectSection("RsaProtectedConfigurationProvider");
local_config.Save(ConfigurationSaveMode.Full);
}
}
For Decrypt AppSettings,
Configuration local_config = WebConfigurationManager.OpenWebConfiguration(HttpContext.Current.Request.ApplicationPath);
ConfigurationSection local_section = config.GetSection(appSettings);
if (local_section.SectionInformation.IsProtected)
{
if (!local_section.ElementInformation.IsLocked)
{
local_section.SectionInformation.UnprotectSection();
local_config.Save(ConfigurationSaveMode.Full);
}
}
Using System.Web.Configuration; For Encryption AppSettings, Configuration local_config = WebConfigurationManager.OpenWebConfiguration(HttpContext.Current.Request.ApplicationPath); ConfigurationSection local_section = config.GetSection(appSettings); if (!local_section.SectionInformation.IsProtected) { if (!local_section.ElementInformation.IsLocked) { string local_encMethod = encryptionProvider.ToString(); local_section.SectionInformation.ProtectSection("RsaProtectedConfigurationProvider"); local_config.Save(ConfigurationSaveMode.Full); } } For Decrypt AppSettings, Configuration local_config = WebConfigurationManager.OpenWebConfiguration(HttpContext.Current.Request.ApplicationPath); ConfigurationSection local_section = config.GetSection(appSettings); if (local_section.SectionInformation.IsProtected) { if (!local_section.ElementInformation.IsLocked) { local_section.SectionInformation.UnprotectSection(); local_config.Save(ConfigurationSaveMode.Full); } } |
2.Using aspnet_regiis Command line tool,
For Encrypt,
C:\>aspnet_regiis -pe "appSettings" -app "/YourAppVirtualDir" -prov "RsaProtectedConfigurationProvider"
For Decrypt,
C:\>aspnet_regiis -pd "appSettings" -app "/YourAppVirtualDir"
For Encrypt, C:\>aspnet_regiis -pe "appSettings" -app "/YourAppVirtualDir" -prov "RsaProtectedConfigurationProvider" For Decrypt, C:\>aspnet_regiis -pd "appSettings" -app "/YourAppVirtualDir" |
Conclusion:
Hope this helps,
Happy Coding.
great post as usual!