我如何加密然后解密Web.config内容

时间:2013-08-04 22:02:40

标签: asp.net

我已在我的Web.config文件中为asp.net mvc Web应用程序添加了以下设置

<appSettings>
    //code goes here
    <add key="ApiUserName" value="testuser" />
    <add key="ApiPassword" value=,,,… />
    <add key="ApiURL" value="http://win-spdev:8400/servlets/AssetServlet" />
  </appSettings>

这些设置用于在我的Controller操作方法中启动API调用: -

    using (var client = new WebClient())
                    {
                        var query = HttpUtility.ParseQueryString(string.Empty);
                        foreach (string key in formValues)
                        {
                            query[key] = this.Request.Form[key];
                        }

query["username"] = System.Web.Configuration.WebConfigurationManager.AppSettings["ApiUserName"];
query["password"] = System.Web.Configuration.WebConfigurationManager.AppSettings["ApiPassword"];
query["assetType"] = "Rack";
query["operation"] = "AddAsset";
string apiurl = System.Web.Configuration.WebConfigurationManager.AppSettings["ApiURL"];
var url = new UriBuilder(apiurl);

我已阅读以下关于加密和解密web.config文件http://msdn.microsoft.com/en-us/library/zhhddkxy.aspx的链接。但我不知道如何在我的上述操作方法中进行加密和解密,如上所述?

1 个答案:

答案 0 :(得分:3)

基本上有两种标准方法,您可以将aspnet_regiis与DPAPI或RSA一起使用。使用RSA执行此操作的优点是,如果您的应用程序在多台计算机上运行,​​您可以使用RSA密钥加密一次,并在所有计算机上使用相同的密钥进行解密,与DPAPI一样,您必须为每台计算机专门加密每台计算机。跑着。

以DPAPI为例,您基本上只需转到框架目录并运行以下命令。

aspnet_regiis -pe“connectionStrings”-app“/ MyApplication”

上面的命令将加密“MyApplication”的连接字符串,这将是IIS中应用程序的名称。现在,这必须在运行应用程序的计算机上运行,​​因此您首先需要将应用程序复制到服务器。使用RSA方法,您可以在您的计算机(或构建服务器)上进行加密,然后部署到您想要的任何计算机上。

您可以在http://msdn.microsoft.com/library/dtkwfdky.aspx

详细了解演练

关于这一点的好处是您不必担心如何访问应用程序设置和连接字符串,您可以像平常一样使用ConfigurationManager.Appsettings和ConfigurationManager.ConnectionStrings,框架将负责这样做解密给你。

相关问题