Шифрование раздела connectionStrings - утилита для app.config
Есть ли утилита, которая будет шифровать именованный раздел конфигурации (или только раздел connectionStrings
) в файле app.config
аналогичным образом, который можно использовать aspnet_regiis
с web.config
файлами?
Я знаю, что это можно сделать в коде - есть примеры кода, но я надеюсь избежать написания приложения для этого.
Ответы
Ответ 1
Вы можете попробовать следующее:
https://magenic.com/thinking/encrypting-configuration-sections-in-net
Короче - переименуем файл app.config
в web.config
- схема идентична, поэтому aspnet_regiis
работает. Вернитесь к app.config
по окончании.
Ответ 2
Старый вопрос, но вот путь Microsoft:
.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);
}
}
Ответ 3
Скомпилируйте это консольное приложение и перетащите на него файл конфигурации. Он выплюнет копию конфигурационного файла с зашифрованными строками подключения.
Обратите внимание, что вы должны зашифровать как тот же пользователь, который будет использовать конфигурационный файл.
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");
}
}
}
Ответ 4
Реализация PowerShell на основе ответа MichelZ:
<#
.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')