I'm working on a project whose configuration system manipulates and deserializes blocks of XML as ConfigurationSection objects. Today we had to make the system support encrypted configuration sections, and we were surprised to find that it wasn't immediately obvious how to do it. The most common answer to the question of "How do I programmatically decrypt a configuration section?" is "Use SectionInformation.UnprotectSection!" Unfortunately, this wouldn't work for us, because we were working with blocks of XML and not ConfigurationSection objects. We needed to decrypt before we could deserialize, but it seemed like we needed to deserialize before we could decrypt. Finally, after much trial and error, many searches, and some Reflector work, we came up with the following:
public static string DecryptConfigurationSectionXml(string xml)
{
XmlDocument document;
string providerName;
ProtectedConfigurationProvider provider;
XmlNode node;
document = new XmlDocument();
document.LoadXml(xml);
providerName = document.DocumentElement.GetAttribute("configProtectionProvider");
if (!String.IsNullOrEmpty(providerName))
{
provider = ProtectedConfiguration.Providers[providerName];
node = provider.Decrypt(document.DocumentElement);
xml = node.InnerXml;
}
return xml;
}
It's extremely simple, but it took a long time to get to this point, so I thought it worth sharing. :)
Cheers,
Colin