2010-04-28 42 views
4

我想保护我的appSettings中的一个键/值对,但不使用像我之前用ProtectSection方法完成的操作,如下所示。是否可以保护appSettings部分中的单个元素而不是整个部分?

var configurationSection = config.GetSection("appSettings"); 
configurationSection.SectionInformation.ProtectSection("DataProtectionConfigurationProvider"); 

理想我想这样做如下:

var configurationElement = config.GetSection("appSettings").GetElement("Protected"); 
configurationElement.ElementInformation.ProtectElement("DataProtectionConfigurationProvider"); 

这是我上操作的例子的appSettings:

<configuration> 
<appSettings> 
    <add key="Unprotected" value="ChangeMeFreely" /> 
    <add key="Protected" value="########"/> 
</appSettings> 
</configuration> 

我一直在寻找,但避风港没有找到办法做到这一点。这可能吗?

回答

4

并非开箱即用 - .NET为您提供了对部分进行加密的能力 - 但不是单个的要素。但是,由于这些只是字符串,因此您自己可以创建一些方案来加密字符串,然后再将其保存到文件中,并在从配置文件读取它之后将其解密。

但是这不会是透明的 - 你必须自己做,你必须明确地做到这一点。

0

当我需要从应用程序设置部分加密一个值时,我遇到了同样的问题。我使用DpapiProtectedConfigurationProvider类的EncryptTextDecryptText私有方法,它允许我加密任何文本值,而不一定要配置元素。

这里是辅助类:

[Test] 
public void EncryptDecryptTest() 
{ 
    var instance = new WebConfigEncryption(); 

    var encrypted = instance.Encrypt("123"); 
    var decrypted = instance.Decrypt(encrypted); 
    Assert.That(decrypted, Is.EqualTo("123")); 
} 

此外,如果你有机会获得XmlNodeXmlElement情况下,你可以使用供应商类的公共方法:

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; 
    } 
} 

使用示例DpapiProtectedConfigurationProvider.Encrypt(XmlNode)DpapiProtectedConfigurationProvider.Decrypt(XmlNode)而不是反射。

相关问题