20160219 .NET中App.config加密实现

来源:互联网 发布:云顶酒店闹鬼 知乎 编辑:程序博客网 时间:2024/05/18 13:11


App.config加密实现:
第一,通过ASP.NET IIS 注册工具 (Aspnet_regiis.exe)实现加密。(加密后的文件只能在加密的机器上解密,拷贝到其他机器上不能解密)
1、将App.config文件重命名为Web.config文件;
2、打开Developer Command Prompt for VS2013输入命令:aspnet_regiis -pef  "connectionStrings"  "Web.config文件所在目录";

貌似不可以将Web.config直接放在根目录加密,如“D:\”,需要有一个上层目录。
3、最后将文件名改回为App.config,放入工程文件目录中(之后看到的都是加密的文件,运行程序的时候会自动解密)。
此法的缺点在于,需要保留一份明码的App.config,以备后面更改信息时使用。


第二,使用RsaProtectedConfigurationProvider加密(加密后的文件只能在加密的机器上解密,拷贝到其他机器上不能解密)

public class UsingRsa{    //Protect the connectionStrings section.    public static void ProtectConfiguration()    {        //Get the application configuration file.        Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);        //Define the Rsa provider name.        string provider = "RsaProtectedConfigurationProvider";        //Get the section to protect.        ConfigurationSection connStrings = config.ConnectionStrings;        if (connStrings != null)        {            if (!connStrings.SectionInformation.IsProtected)            {                if (!connStrings.ElementInformation.IsLocked)                {                    //Protect the section.                    connStrings.SectionInformation.ProtectSection(provider);                    connStrings.SectionInformation.ForceSave = true;                    config.Save(ConfigurationSaveMode.Full);                }            }        }    }    //Unprotect the connectionStrings section.    public static void UnProtectConfiguration()    {        //Get the application configuration file.        Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);        //Get the section to unprotect.        ConfigurationSection connStrings = config.ConnectionStrings;        if (connStrings != null)        {            if (connStrings.SectionInformation.IsProtected)            {                if (!connStrings.ElementInformation.IsLocked)                {                    //Unprotected the section                    connStrings.SectionInformation.UnprotectSection();                    connStrings.SectionInformation.ForceSave = true;                    config.Save(ConfigurationSaveMode.Full);                }            }        }    }}



0 0
原创粉丝点击