public
static
class
ProtectConfigFileUtil
{
/// <summary>
/// 加密配置节示例,加密 ConnectionStrings 和 AppSettings
/// </summary>
[Obsolete( " 这个方法只是示例 " )]
public static void ProtectConnectionStringsAndAppSettings(HttpContext context)
{
Configuration config = WebConfigurationManager.OpenWebConfiguration(context.Request.ApplicationPath);
// ' Define the Dpapi provider name.
String provider = " DataProtectionConfigurationProvider " ;
ProtectSection(config.ConnectionStrings, provider);
ProtectSection(config.AppSettings, provider);
config.Save(System.Configuration.ConfigurationSaveMode.Modified);
}
/// <summary>
/// 加密一个配置节
/// </summary>
/// <param name="section"></param>
/// <param name="provider"></param>
/// <returns></returns>
public static bool ProtectSection(ConfigurationSection section, String provider)
{
if (section != null
&& ! section.SectionInformation.IsProtected
&& ! section.ElementInformation.IsLocked)
{
// ' Protect the section.
section.SectionInformation.ProtectSection(provider);
section.SectionInformation.ForceSave = true ;
return true ;
}
return false ;
}
/// <summary>
/// 解密一个配置节
/// </summary>
/// <param name="section"></param>
/// <returns></returns>
public static bool UnprotectSection(ConfigurationSection section)
{
if (section != null
&& ! section.SectionInformation.IsProtected
&& ! section.ElementInformation.IsLocked)
{
// ' Protect the section.
section.SectionInformation.UnprotectSection();
section.SectionInformation.ForceSave = true ;
return true ;
}
return false ;
}
}
{
/// <summary>
/// 加密配置节示例,加密 ConnectionStrings 和 AppSettings
/// </summary>
[Obsolete( " 这个方法只是示例 " )]
public static void ProtectConnectionStringsAndAppSettings(HttpContext context)
{
Configuration config = WebConfigurationManager.OpenWebConfiguration(context.Request.ApplicationPath);
// ' Define the Dpapi provider name.
String provider = " DataProtectionConfigurationProvider " ;
ProtectSection(config.ConnectionStrings, provider);
ProtectSection(config.AppSettings, provider);
config.Save(System.Configuration.ConfigurationSaveMode.Modified);
}
/// <summary>
/// 加密一个配置节
/// </summary>
/// <param name="section"></param>
/// <param name="provider"></param>
/// <returns></returns>
public static bool ProtectSection(ConfigurationSection section, String provider)
{
if (section != null
&& ! section.SectionInformation.IsProtected
&& ! section.ElementInformation.IsLocked)
{
// ' Protect the section.
section.SectionInformation.ProtectSection(provider);
section.SectionInformation.ForceSave = true ;
return true ;
}
return false ;
}
/// <summary>
/// 解密一个配置节
/// </summary>
/// <param name="section"></param>
/// <returns></returns>
public static bool UnprotectSection(ConfigurationSection section)
{
if (section != null
&& ! section.SectionInformation.IsProtected
&& ! section.ElementInformation.IsLocked)
{
// ' Protect the section.
section.SectionInformation.UnprotectSection();
section.SectionInformation.ForceSave = true ;
return true ;
}
return false ;
}
}