是否有一个实用程序可以加密connectionStrings
文件中的命名配置部分(或仅app.config
部分),其方式类似于aspnet_regiis
web.config
文件?
我知道这可以在代码中完成 - 那里有代码示例,但我希望避免为此编写应用程序。
答案 0 :(得分:18)
您可以尝试以下操作:
https://magenic.com/thinking/encrypting-configuration-sections-in-net
简而言之 - 将app.config
文件重命名为web.config
- 架构相同,因此aspnet_regiis
有效。完成后重命名为app.config
。
答案 1 :(得分:6)
老问题,但这是微软的方式:
.NET 2.0: http://msdn.microsoft.com/en-us/library/89211k9b(v=vs.80).aspx
.NET 3.5: http://msdn.microsoft.com/en-us/library/ms254494(v=vs.90).aspx (部分"使用受保护的配置加密配置文件部分")
在app.config文件上切换加密:
static void ToggleConfigEncryption(string exeConfigName)
{
// Takes the executable file name without the
// .config extension.
try
{
// Open the configuration file and retrieve
// the connectionStrings section.
Configuration config = ConfigurationManager.
OpenExeConfiguration(exeConfigName);
ConnectionStringsSection section =
config.GetSection("connectionStrings")
as ConnectionStringsSection;
if (section.SectionInformation.IsProtected)
{
// Remove encryption.
section.SectionInformation.UnprotectSection();
}
else
{
// Encrypt the section.
section.SectionInformation.ProtectSection(
"DataProtectionConfigurationProvider");
}
// Save the current configuration.
config.Save();
Console.WriteLine("Protected={0}",
section.SectionInformation.IsProtected);
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
答案 2 :(得分:5)
编译此控制台应用程序,并将配置文件拖到其上。它将吐出配置文件的副本,并对其连接字符串进行加密。
请注意,您必须以使用配置文件的同一用户进行加密。
using System;
using System.Configuration;
using System.IO;
namespace ConnectionStringEncryptor
{
class Program
{
static void Main(string[] args)
{
if (args.Length == 0)
{
throw new ArgumentException("Please supply a config file to encrypt");
}
string originalConfigFilePath = args[0];
AppDomain.CurrentDomain.SetData("APP_CONFIG_FILE", originalConfigFilePath);
Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
ConnectionStringsSection connectionStringsSection = (ConnectionStringsSection)config.GetSection("connectionStrings");
connectionStringsSection.SectionInformation.ProtectSection("DataProtectionConfigurationProvider");
config.SaveAs(originalConfigFilePath + ".encrypted");
}
}
}
答案 3 :(得分:2)
基于MichelZ答案的PowerShell实现:
<#
.SYNOPSIS
Encrypts a section in .NET app configuration file.
#>
function Protect-DotNetConfigSection
{
[CmdletBinding()]
param
(
# Path to .exe file.
[Parameter(Mandatory = $true)]
[string] $ExePath,
# List of section names.
[Parameter(Mandatory = $true)]
[string[]] $Sections
)
$config = [System.Configuration.ConfigurationManager]::OpenExeConfiguration($ExePath)
foreach ($section in $Sections)
{
$config.GetSection($section).SectionInformation.ProtectSection('DataProtectionConfigurationProvider')
}
$config.Save()
}
Protect-DotNetConfigSection 'C:\MyApp\MyApp.exe' 'connectionStrings'
Protect-DotNetConfigSection 'C:\MyApp\MyApp.exe' @('connectionStrings', 'appSettings')