能否保护appSettings部分中的单个元素而不是整个部分?

6

我希望保护我的应用程序设置中的一个键/值对,但不保护其他键/值对,使用之前使用的ProtectSection方法来实现,如下所示。

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>

我一直在搜索,但没有找到实现这个目标的方法。这个可行吗?

2个回答

6

不是开箱即用的 - .NET提供了加密部分的能力,但不能加密单个元素。然而,由于这些只是字符串,您完全可以自己创建一些方案,在保存到文件之前对字符串进行加密,然后在从配置文件中读取后进行解密。

但这并不是透明的 - 您必须自己完成,并且必须明确地完成。


0

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

这是帮助类:

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

使用示例:

[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实例,您可以使用提供程序类的公共方法:DpapiProtectedConfigurationProvider.Encrypt(XmlNode)DpapiProtectedConfigurationProvider.Decrypt(XmlNode),而不是反射。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接