65.9K
CodeProject 正在变化。 阅读更多。
Home

加密 Windows Forms 应用程序的 app.config 文件

starIconstarIconstarIconstarIcon
emptyStarIcon
starIcon

4.08/5 (8投票s)

2007 年 3 月 30 日

CPOL

2分钟阅读

viewsIcon

327384

downloadIcon

5292

加密 Windows Forms 应用程序的 app.config 文件

引言

ASP.NET 提供自动加密 web.config 中部分内容的功能。 但对于 WinForm 应用程序的 app.config 似乎无法做到这一点。 这部分属实:WinForms 不提供配置它的工具。 但这是可以做到的。 一切都是 .NET 的,不是吗? 那么我们该怎么做呢? 继续阅读,看看如何操作。

Using the Code

首先让我解释一下 .NET 中配置文件的相关内容。app.configweb.config 被分成多个部分。 加密和解密操作是对各个部分执行的,而不是对整个文件执行。

开发人员可以通过定义自定义部分来扩展配置文件。 这可以通过向 configSections 元素或 sectionGroup 元素添加 section 标签来完成,如下例所示。 section 元素的 name 属性指定新部分的名称。 type 属性指定处理 configuration 部分的处理程序:它从该部分中获取数据。 正如您在下面的示例中看到的,我实现了这两种情况。

<?xml version="1.0" encoding="utf-8" ?>
<configuration> 
    <configSections>
        <section name="Vault" 
                 type="System.Configuration.NameValueSectionHandler" />
        <sectionGroup name="applicationSettings" 
                    type="System.Configuration.ApplicationSettingsGroup, System, 
                    Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" >
            <section name="EncryptConnStringsSection.My.MySettings" 
                    type="System.Configuration.ClientSettingsSection, System, 
                    Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" 
                    requirePermission="false" />
        </sectionGroup>
    </configSections>
    <connectionStrings>
        <add name="EncryptConnStringsSection.My.MySettings.testConn"
            connectionString="Data Source=someserver;Initial 
                             Catalog=ProjectX_Dev;Integrated Security=True" />
    </connectionStrings>

现在我已经解释了如何在 app.config 中创建部分,让我们继续展示如何加密部分。 这确实是一个简单的操作。 一旦一个部分被加密,您就不必担心解密它。 .NET Framework 会自动为您完成。 这是一个透明的操作,就像您没有加密该部分一样。

configuration 命名空间包含一个代表部分的类。 这个类被称为 ConfigurationSection。 此类的一个成员是 ElementInformation 属性。 此属性获取有关部分的信息,并且它具有在其上定义的 ProtectSection 方法。 此方法加密该部分。 开箱即用,通过提供程序支持两种加密算法

  • DPAPIProtectedConfigurationProvider
  • RSAProtectedConfigurationProvider

默认的提供程序是 RSAProtectedConfigurationProvider。 您可以通过将 nothing/null 作为参数传递给 ProtectSection 方法来使用默认提供程序。
我编写了以下类来演示这个方法

Imports System.Configuration

''' <summary>
''' This class protects (encrypts) a section in the applications configuration file.
''' </summary>
''' <remarks>The <seealso cref="RsaProtectedConfigurationProvider"/> 
''' is used in this implementation.</remarks>
Public Class ConfigSectionProtector

    Private m_Section As String

    ''' <summary>
    ''' Constructor.
    ''' </summary>
    ''' <param name="section">The section name.</param>
    Public Sub New(ByVal section As String)
        If String.IsNullOrEmpty(section) Then _ 
            Throw New ArgumentNullException("ConfigurationSection")

        m_Section = section
    End Sub

    ''' <summary>
    ''' This method protects a section in the applications configuration file. 
    ''' </summary>
    ''' <remarks>
    ''' The <seealso cref="RsaProtectedConfigurationProvider" /> 
    ''' is used in this implementation.
    ''' </remarks>
    Public Sub ProtectSection()
        ' Get the current configuration file.
        Dim config As Configuration = ConfigurationManager.OpenExeConfiguration
                        (ConfigurationUserLevel.None)
        Dim protectedSection As ConfigurationSection = config.GetSection(m_Section)

        ' Encrypts when possible
        If ((protectedSection IsNot Nothing) _
        AndAlso (Not protectedSection.IsReadOnly) _
        AndAlso (Not protectedSection.SectionInformation.IsProtected) _
        AndAlso (Not protectedSection.SectionInformation.IsLocked) _
        AndAlso (protectedSection.SectionInformation.IsDeclared)) Then
            ' Protect (encrypt)the section.
            protectedSection.SectionInformation.ProtectSection(Nothing)
            ' Save the encrypted section.
            protectedSection.SectionInformation.ForceSave = True
            config.Save(ConfigurationSaveMode.Full)
        End If
    End Sub
End Class 

正如您所看到的,这个类也有一个方法 ProtectSection。 基本上,它从 app.config 中获取部分信息,并检查是否可以加密。 如果可以,它使用默认的加密提供程序来保护该部分,并保存它。 完成了。

保护或取消保护 connectionstrings 更简单。 可以使用以下代码示例完成

' Connection string encryption
Dim config As Configuration = ConfigurationManager.OpenExeConfiguration
                    (ConfigurationUserLevel.None)      
config.ConnectionStrings.SectionInformation.ProtectSection(Nothing)
' We must save the changes to the configuration file.
config.Save(ConfigurationSaveMode.Full, True)  

历史

  • 2007-03-30:初始版本
  • 2007-04-12:添加了指向我的 博客 的链接。 也许你会喜欢它。 请告诉我。
  • 2007-04-18:更新了示例项目
  • 2007-04-21:更新了最后一个代码示例
© . All rights reserved.