首先添加引用:usingSystemWebConfiguration;
加密操作如下:
PRivatevoidProtectSection(stringsectionNamestringprovider)
{
Configurationconfig=
WebConfigurationManager
OpenWebConfiguration(RequestapplicationPath);
ConfigurationSectionsection=configGetSection(sectionName);
if(section!=null&&!sectionSectionInformationIsProtected)
{
sectionSectionInformationProtectSection(provider);
configSave();
}
}
解密操作如下:
privatevoidUnProtectSection(stringsectionName)
{
Configurationconfig=
WebConfigurationManager
OpenWebConfiguration(RequestApplicationPath);
ConfigurationSectionsection=configGetSection(sectionName);
if(section!=null&§ionSectionInformationIsProtected)
{
sectionSectionInformationUnprotectSection();
configSave();
}
}
实践:
加密前的配置文件:
<?xmlversion=""?>
<configuration>
<appSettings>
<addkey="name"value="shy"/>
<addkey="address"value="cnblogs"/>
</appSettings>
<systemweb>
<compilationdebug="true"/>
</systemweb>
</configuration>
加密后的配置文件(Webconfig):
<?xmlversion=""?>
<configuration>
<appSettingsconfigProtectionProvider="DataProtectionConfigurationProvider">
<EncryptedData>
<CipherData>
<CipherValue>
AQAAANCMndBFdERjHoAwE/Cl+s
BAAAABiATlNkEUGEfXyWGLXg
QAAAACAAAAAAADZgAAqAAAABAAA
ABIhxMWlazAntwIIpSTCDXAAAA
AASAAACgAAAAEAAAAPz/YKYxc
b+hfqdrfkLgAAAAXIeyc+WSx
AfsDWvnC/fXsGTAnYeUgaCov
enGFTHHsHgLiqKregFPYzGR
vWxrez/VwOmJIeSEFKrcXej
NnHLkgiNRkntLNZlZtTscZ
wuVKAjsmiWsGBzGntL/
UGHLELigrJcrYJ+lsjOscExQnv
HGvAEfxpD+tEiFBtgXeHsFkQX
cqGySshxvCtGUNUCZmEAhBh
UsAFkPIYqelYHd+ma/xPetqw
GIblawbWNDEfrzJPwnkfmpNqR
hXijKImipwXbDVYyoUAAAAsD
suYNOhJqAjJac/eUCsks=
</CipherValue>
</CipherData>
</EncryptedData>
</appSettings>
<systemweb>
<compilationdebug="true"/>
</systemweb>
</configuration>