Encrupt/Protect Custom Configuration Section

Illustrates how to encrypt custom configuration section in the service OnStart event:

protected override void OnStart(string[] args)
{
	try
	{			    
		string sectionName = "SectionNameToSecure";
		
		Configuration config = 
				ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
		ConfigurationSection section = config.GetSection(sectionName);
		if (!section.SectionInformation.IsProtected)
		{
			section.SectionInformation.ProtectSection("RsaProtectedConfigurationProvider");
			section.SectionInformation.ForceSave = true;
			config.Save(ConfigurationSaveMode.Full);

			// Reset configuration object!
			ConfigurationManager.RefreshSection(sectionName);
		}                
	}
	catch (Exception ex)
	{
		// Do exception tracing here
		this.Stop();
	}
}
Advertisements