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

52

我在尝试加密app.config中的连接字符串时遇到了问题。 我有一些代码可以保护app.config的connectionStrings部分,但密码仍以明文形式显示。

我需要加密连接字符串,这样在部署时就不会以明文形式显示。我在SO上看到了类似于web.config的问题,但没有针对app.config。


1
请注意,如果您使用ProtectSection()加密连接字符串,我只需复制您的加密.config文件,将其用于我的应用程序并调用UnprotectSection()。这将以明文形式返回您原始的连接字符串。 - Run CMD
只要在同一台计算机上,@RunCMD 是可以运行的。根据微软文档的说法,“连接字符串只能在加密它的计算机上进行解密。”... 参考链接:https://learn.microsoft.com/en-us/dotnet/framework/data/adonet/connection-strings-and-configuration-files - Tim Friesen
7个回答

65

你可以轻松地将与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:\<包含你的web.config的文件夹> (停留在文件夹级别,不要输入尾随的“”)
  3. 将web.config重新命名为app.config

你可以在记事本中打开它以查看已加密的文件。 在Visual Studio中,你会发现它已被解密。 你可以像未加密时一样使用连接字符串。(请注意,它只能在加密的计算机上解密。)


8
完美!直指要点!解密: %windir%\Microsoft.NET\Framework\v2.0.50727\aspnet_regiis -pdf "connectionStrings" c:\folder - Alex
5
这对我很有效,实现起来比被采纳的答案要容易得多。 - mgnoonan
3
对我来说,我必须以管理员身份运行命令提示符才能使它工作。 - Jim Simson
1
我使用了一种方法来更改加密的字符串,但是在将app.config文件重新填充回我的VS 2012后,它显示错误:“元素ConnectionString在命名空间http://www.w3.org/2001/04/xmlenc#Element中有无效的子元素EncryptedData”。感到无助! - ZahidKakar
22
此功能仅适用于加密文件的同一台计算机;如果在另一台计算机上部署,则无法使用,来自微软笔记 - wpcoder
显示剩余8条评论

25
请查看这篇文章,它有一些非常有用的示例。你基本上需要使用System.Configuration.SectionInformation.ProtectSection来帮助你。此外,也可以参考实现受保护的配置

2
这个方法可用于其中包含DataSets和TableAdapters的情况吗?它们选择存储在您的app.config中的连接字符串...如果它被加密了,它仍然会自动解密吗? - a7mad.3ezz
2
这基本上是一个仅包含链接的答案。如果链接失效,您介意在答案中添加链接的要点以保持答案有用吗? - Gert Arnold

5

• 将 App.config 文件重命名为 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" 

解密:

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" 

对于错误:

在配置中添加以下内容:xmlns="http://schemas.microsoft.com/.NetConfiguration/v2.0"

像这样:

enter image description here

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


4

此外,如果有人想要在Web Farm中加密和解密连接字符串,请按照以下步骤进行:

  1. Create an RSA key: aspnet_regiis -pc "MyKeys" -exp

  2. Grant access for application pool identity to this key: aspnet_regiis -pa "MyKeys" "IIS AppPool\ApplicationPoolName" -full

  3. Add RSA provider to the web.config:

    <configuration>
        <configProtectedData>
            <providers>
                <add name="MyProvider" 
                     type="System.Configuration.RsaProtectedConfigurationProvider, System.Configuration, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a, processorArchitecture=MSIL" 
                     keyContainerName="MyKeys" 
                     useMachineContainer="true" />
            </providers>
        </configProtectedData>
    </configuration>
    
  4. Encrypt web.config by using the RSA provider: aspnet_regiis -pe "connectionStrings" -app "/MyApplication" -prov "MyProvider" Note: You can use the alternative syntax like the one we did for a single server scenario. Example: ASPNET_REGIIS -pef "connectionStrings" "D:\inetpub\wwwroot\applicationFolder" -prov "MyProvider"

  5. Open the web.config and confirm that the connection string is encrypted

  6. Test the site and confirm that it is working

  7. Try decrypting the web.config. Create a test.aspx file with the code below inside. Browse it to see the decrypted file

  8. Export the RSA key to the C drive: aspnet_regiis -px "MyKeys" "c:\keys.xml" -pri

  9. Copy this file to the second server in the web farm

  10. Import it in that server: aspnet_regiis -pi "MyKeys" "c:\keys.xml"

  11. Grant access to this key (same as Step 2)

  12. Test the application in the second server

来源: 如何加密和解密连接字符串


3
定义config文件的位置
Configuration config  = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);

如果你想加密 connectionStrings

config.ConnectionStrings.SectionInformation.ProtectSection(Nothing);

您需要了解应用程序配置部分。

因此,如果您想加密 AppSettings

config.AppSettings.SectionInformation.ProtectSection(Nothing);

enter image description here


1
这个可以运行,但在我的情况下,我必须将“Nothing”替换为“DataProtectionConfigurationProvider”。 - Edvan Souza
1
@Salen-Ahmed 你忘记保存配置了。config.save() - vibs2006

2
自动化的方法:
项目设置 > 编译 > 构建事件 > 编辑后生成
粘贴以下代码:
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文件。


发布怎么样? - Falakienos

0
经过数小时的研究,我找到了一个合理的解决方案:
问题在于你的应用程序需要包含解密密钥和解密算法才能解密并使用连接字符串。假设即使是初级开发人员也无法通过调试代码、逐步执行解密并最终获取未加密的字符串,这是很危险的。
将机密信息(如连接字符串、密码、API密钥)存储在配置文件中是不安全的做法,强烈反对这种做法。相反,你应该使用“机密管理器”服务——这是一个安全的在线服务,可以存储你的密码,并在需要时让你检索它们。
当使用机密管理服务时,没有机密、解密密钥或算法存储在你的源代码中。检索机密就像这样简单:
对于Azure Key Vault:
 var keyVaultUrl = "https://<your-key-vault-name>.vault.azure.net/";
 var credential =  new DefaultAzureCredential();    
 var client = new SecretClient(vaultUri: new Uri(keyVaultUrl), credential);    
 KeyVaultSecret secret = client.GetSecret("<your-secret-name>");    
 Console.WriteLine($"{secret.Name}: {secret.Value}");

对于 AWS Secrets Manager(省略了一些错误处理代码):

 var client = new AmazonSecretsManagerClient(accessKeyId, secretAccessKey, 
                                             RegionEndpoint.APSoutheast2);
 var request = new GetSecretValueRequest {
     SecretId = secretName
 };
 GetSecretValueResponse response = null;
 response = client.GetSecretValueAsync(request).Result;

您还可以搜索替代的秘密管理器和实现,如Google Cloud Secret Manager或其他。

与本地存储秘密相比,这种方法有很多优点:

  • 您不必在Prod / Staging / Dev环境的配置文件中存储不同的值 - 只需读取适当命名的密钥(例如“[Dev | Prod | Stag]DBPassword”)

  • 仅有少数人可以访问非常重要的秘密(例如,我不知道,转移全球Deus账户中所有$$$到E-Coin钱包的授权码),他们的访问权限可以随时撤销

  • 如果有人窃取了您的源代码(不满的员工,意外泄漏),则没有任何密码泄漏

  • 更改密码很容易 - 您只需使用could管理控制台更新它并重新启动应用程序

如何使用AWS Secrets Manager在.Net Core应用程序中存储和读取密码

.NET Core 应用程序中如何使用 Azure Key Vault 安全地存储和检索敏感信息

鸣谢并感谢 @smartial-arts参考资料第二个答案


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接