配置文件-正在加密连接字符串



我正在尝试开发一个连接到SQL数据库的C#Winform应用程序。

到目前为止,我能够将最敏感的数据从XML配置文件移动到外部XML配置文件,但仅此而已

我要做的最后一件事是加密该文件,因为许多人都可以访问应用程序所在的目录。

我的主要[APP]配置文件如下:

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<configSections>
</configSections>
<connectionStrings configSource="conn_string.config"/>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.7.2" />
</startup>
</configuration>

还有我的[conn_string]外部配置文件,我试图在其中隐藏一个连接字符串:

<?xml version="1.0" encoding="utf-8" ?>
<connectionStrings>
<add name="myConnectionStringName"
providerName="System.Data.SqlClient"
connectionString="Data Source=ServerName;Initial 
Catalog=InitialDatabaseName;User=UserName;Password=MyPassword;Application Name=MyAppName" />
</connectionStrings>

现在,当谈到加密时,我读到asp-netregis.exe只查找名为"web"的文件所以我暂时将我的"conn_string"文件重命名为"web">

并尝试了加密(通过开发者命令行VS(:

aspnet_regiis -pef "connectionStrings" "path_to_my_conn_string_file"

结果是:~我的翻译

The web.config file doesn't contain a configuration tag 

所以我添加了一个这样的:

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<connectionStrings>
<add name="myConnectionStringName"
providerName="System.Data.SqlClient"
connectionString="Data Source=ServerName;Initial 
Catalog=InitialDatabaseName;User=UserName;Password=MyPassword;Application Name=MyAppName" />
</connectionStrings>
</configuration>

现在它抱怨:~再次我的翻译

File format configSource must be an element conatining section name

您正在采取的使用aspnet_Regiis的步骤实际上是针对Internet Information Server(IIS(中托管的web应用程序的。它正在寻找的文件实际上是"web.config"。你提到正在构建的应用程序是一个winforms应用程序,而不是一个web应用程序。常规的winforms应用程序通常通过名为"app.config"的文件进行配置。Visual Studio可能已经为您创建了一个基本的app.config,具体取决于您使用的版本。

您可以通过临时将app.config重命名为web.config,然后使用指向"虚假"web.config的确切路径的标志调用aspnet_Regiis来"欺骗"aspnet_Regiis加密您的配置文件:

为了简单起见,假设您的初始app.config位于c:\MyPrograms\MyApp中。

  1. 将app.config重命名为web.config
  2. 在管理命令提示符下,将当前目录设置为c:\windows\micrsoft.net\framework\v4.0.30319
  3. 调用aspnet_regiis,使用"-pef"开关指示该工具加密web.config的特定部分:

    aspnet_regiis-pef"connectionStrings"c:\MyPrograms\MyApp

  4. 如果看到"成功"消息,请将web.config重命名回app.config,然后运行应用程序。NET应该在运行时自动解密该机器上的连接字符串。

如果需要将此应用程序放在其他计算机上,则可能需要考虑设置一个可以安装在其他计算机中的通用加密密钥,并在web.config中定义一个利用该密钥的提供程序。但现在,让我们让基本流程在本地工作,然后在知道这一部分工作后再担心其他组件。

希望这能有所帮助!

最新更新