加密app.config中的连接字符串

问题描述 投票:40回答:5

我在app.config中加密连接字符串时遇到问题。我的代码将保护app.config的connectionStrings部分,但密码仍以纯文本显示。

我需要加密连接字符串,因此在部署时它不是纯文本。我在web.config上看到了类似的问题,但不是app.config。

c# sql-server-2008 app-config
5个回答
23
投票

看看This Article它有一些非常有用的例子。你基本上都在寻找System.Configuration.SectionInformation.ProtectSection来帮助你。

还可以看看Implementing Protected Configuration


50
投票

您可以轻松地应用与web.config相同的解决方案,您只需将app.config重命名为web.config,使用aspnet_regiis工具进行加密,然后将其重命名为app.config。

  1. 将app.config重命名为web.config
  2. 打开命令提示符并键入: %windir%\Microsoft.NET\Framework\v2.0.50727\aspnet_regiis -pef "connectionStrings" c:\<folder containing your web.config>(在文件夹级别停止,不要将尾随“\”)
  3. 将web.config重命名为app.config

您可以在记事本中打开它以查看加密文件。在visual studio中,您将看到它已被解密。您可以像使用未加密的方式一样使用连接字符串。


3
投票

定义config文件的位置

Configuration config  = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);

如果你想加密connectionStrings

config.ConnectionStrings.SectionInformation.ProtectSection(Nothing);

你必须知道app配置部分

所以,如果你想加密AppSettings

config.AppSettings.SectionInformation.ProtectSection(Nothing);

enter image description here


2
投票

一种自动化的方法:

ProjectSettings>编译> BuildEvents>编辑后期构建

粘贴下面的代码:

SET ApplicationName=YourAppWithoutExtention
echo.
echo POST BUILD ACTIONS
echo ====================

if EXIST web.config (
    echo Deleting web.config
    DEL web.config
)

echo Renaming %ApplicationName%.exe.config to web.config
REN %ApplicationName%.exe.config web.config

echo Running aspnet_regis against webconfig
SET rpath=%windir%\Microsoft.NET\Framework\v2.0.50727\aspnet_regiis -pef "connectionStrings" "$(TargetDir)
SET rpath=%rpath:~0,-1%"
echo Path: %rpath%
%rpath%

echo Renaming web.config to %ApplicationName%.exe.config 
REN web.config %ApplicationName%.exe.config

echo Done.

用您的应用名称替换“YourAppWithoutExtention”。

然后每次构建时,它都会自动加密你的app.config。


2
投票

•重命名App.config file to web.config<br>•以管理员身份运行命令提示符:

对于加密:

C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\aspnet_regiis.exe -pef "connectionStrings"你的项目位置在引号和-prov "DataProtectionConfigurationProvider"

例如:

C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\aspnet_regiis.exe -pef "connectionStrings" "D:\location\location1\location" -prov "DataProtectionConfigurationProvider" 

对于Decrypt:

C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\aspnet_regiis.exe -pdf "connectionStrings"你的项目位置在报价内。

例如:

C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\aspnet_regiis.exe -pdf "connectionStrings" "D:\location1\location" 

出错:

在Configuration xmlns="http://schemas.microsoft.com/.NetConfiguration/v2.0"中添加它

像这样:

enter image description here

•最后,将web.config重命名为App.Config

© www.soinside.com 2019 - 2024. All rights reserved.