2017-03-17 34 views
0

我試圖根據this page來保護.Net桌面應用的配置文件ProtectedConfigurationProvider。我實現了一個新的提供者類,爲了保護配置節,我將節節點反序列化爲模型,對內部字符串值進行加密,然後將加密模型序列化到節點節點,並將其放入新的「EncryptedData」元素中,反之亦然。 例如,我在配置文件中的「的appSettings」部分:ProtectedConfigurationProvider.Decrypt在解密配置節節點時保持解除狀態

<appSettings> 
    <add key="test key" value="test value" /> 
</appSettings> 

加密後:

<appSettings configProtectionProvider="customProtectionProvider"> 
    <EncryptedData> 
    <appSettings> 
     <add key="6ZefRBry+Q" value="6ZefRB2w7OuU" /> 
    </appSettings> 
    </EncryptedData> 
</appSettings> 

這裏是我的問題:當我嘗試解密受保護的配置數據,解密我的自定義提供程序中的方法總是會被解僱,當我反序列化加密部分xml模型,然後進入反序列化部分。在提供者的解密方法

  1. 負載配置,並得到 「的appSettings」 部分

    Configuration config = 
        ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None); 
    ConfigurationSection appSettingsSection = 
        config.GetSection("appSettings"); // fire Decrypt method here 
        // ......
  2. var sectionModel = ConfigurationBase.Deserialize(encryptedNode);

  3. 反序列化

    
    //...get custom section type by encryptedNode.Name 
    Type sectionType = typeof(Section.AppSettingsSection); 
    XmlSerializer serializer = new XmlSerializer(sectionType); // fire Decrypt method here and then infinite loops 
    

這裏是我的AppSettingsSection類:

[XmlRoot("appSettings")] 
public class AppSettingsSection : ConfigurationBase 
{ 
    [XmlAttribute("file")] 
    public string File { get; set; } 

    [XmlElement("add")] 
    public List<KeyValueNode> Settings { get; set; } 

    protected override void encryp() 
    { 
     // ...... 
    } 

    protected override void decrypt() 
    { 
     // ...... 
    } 
} 

我不知道爲什麼這種類型的創建XmlSerializer的會叫ProtectedConfigurationProvider的解密方法。

有沒有解決方法?

+0

這太奇怪了......當我在vs2010中構建項目時,不像以前的vs2012,一切正常。 – runerback

回答

0

我下載的System.Xml.Serialization的調試符號,並踏進去,然後我發現後65行TempAssembly類,ProtectedConfigurationProvider.Decrypt方法將被調用,所以我檢查了TempAssembly.UseLegacySerializerGeneration財產,在吸氣叫System.Xml.Serialization.AppSettings類,它試圖從ConfigurationManager.AppSettings配置部分獲取值,但之前我輸入了它,所以Decrypt方法再次被調用。

最後,解決方案是避免加密appSettings cofnig部分。