I had the same problem when I needed to encrypt one value from the application settings section. I used the private EncryptText and DecryptText methods of the EncryptText class, which allowed me to encrypt any text values, and not necessarily configuration items.
Here is a helper class:
public class WebConfigEncryption { private readonly DpapiProtectedConfigurationProvider _provider; private readonly MethodInfo _encryptTextMethod; private readonly MethodInfo _decryptTextMethod; public WebConfigEncryption() { _provider = new DpapiProtectedConfigurationProvider(); _encryptTextMethod = _provider.GetType().GetMethod("EncryptText", BindingFlags.Instance | BindingFlags.NonPublic); _decryptTextMethod = _provider.GetType().GetMethod("DecryptText", BindingFlags.Instance | BindingFlags.NonPublic); } public string Encrypt(string value) { var encryptedValue = value != null ? (string)_encryptTextMethod.Invoke(_provider, new object[] { value }) : null; return encryptedValue; } public string Decrypt(string value) { var decryptedValue = value != null ? (string)_decryptTextMethod.Invoke(_provider, new object[] { value }) : null; return decryptedValue; } }
Usage example:
[Test] public void EncryptDecryptTest() { var instance = new WebConfigEncryption(); var encrypted = instance.Encrypt("123"); var decrypted = instance.Decrypt(encrypted); Assert.That(decrypted, Is.EqualTo("123")); }
Also, if you have access to XmlNode or XmlElement instances, you can use the public methods of the provider class: DpapiProtectedConfigurationProvider.Encrypt(XmlNode) and DpapiProtectedConfigurationProvider.Decrypt(XmlNode) instead of reflection.
source share