none
Not clear about encrypting connection string in app.config RRS feed

  • Question

  • I am going to implement encryption of my connection string in my app.config file for the first time. 

    This is the code I will be referencing  from MSDN:

    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);
    }
    }

    My question is: Does this encrypt and decrypt the connection in the app.config.exe file each time the program is run? I am not exactly clear on how to use this. From my understanding I write my connection string into my app.config file located in my solution explorer then call this code on application load up and once it is in production the config file turns into a config.exe which is always encrypted from prying eyes? I am not sure how to connect saving the connection string during development to the encryption process.

    • Moved by Lisa Zhu Thursday, April 25, 2013 5:06 AM CLR related
    Tuesday, April 23, 2013 7:06 PM

Answers

  • Hi Marv,

    Here is a way to encrypt the config:

    1. Make a tool with above code.

    To encrypt the config file, you only need the following code in this tool:

    section.SectionInformation.ProtectSection(
    "DataProtectionConfigurationProvider");
    
    // Save the current configuration.
    config.Save();

    2. Copy the original config file to the target machine.

    3. Run this tool on the target machine and the unecrypted config file.

    4. Keep the encrypted config file on the target machine, and remove the original one.

    I hope this is clear.

    Best regards,


    Mike Feng
    MSDN Community Support | Feedback to us
    Develop and promote your apps in Windows Store
    Please remember to mark the replies as answers if they help and unmark them if they provide no help.

    Thursday, April 25, 2013 8:30 AM
    Moderator
  • You can have a much better approach for encryption sections in config files using: Windows Data Protection application programming interface (DPAPI).

    DPAPI protected configuration provider and the Aspnet_regiis.exe tool can be used to encrypt sections of configuration files. The DPAPI protected configuration provider supports machine-level and user-level stores for key storage.

    Configuration sections that usually contain sensitive information that you need to encrypt are the following:

    • <appSettings>. This section contains custom application settings
    • <connectionStrings>. This section contains connection strings
    • <identity>. This section can contain impersonation credentials
    • <sessionState>. The section contains the connection string for the out-of-process session state provider

    To encrypt the connectionStrings section in Web.config:

    • Create a new Web site, directory to be configured as a virtual directory
    • Add a configuration file (ex. web.config) to this directory
    • Add connectionString similar to the following example
    <connectionStrings>
      <add name="MyLocalSQLServer" 
           connectionString="Initial Catalog=aspnetdb;
           data source=localhost;Integrated Security=SSPI;" 
           providerName="System.Data.SqlClient"/>
    </connectionStrings>

    • To encrypt the connectionStrings section, run the following command from a .NET command prompt (where MachineDPAPI is the name of the IIS virtual directory):

    aspnet_regiis -pe "connectionStrings" -app "/MachineDPAPI" -prov "DataProtectionConfigurationProvider"

    v  The Aspnet_regiis.exe utility tool is located in the following directory: %WinDir%\Microsoft.NET\Framework\<versionNumber>

    v  The DPAPI machine key is stored at the following location: %windir%\system32\Microsoft\Protect\S-1-5-18

    • Your modified configuration file, with the connectionStrings section encrypted, will look like below example:
    <connectionStrings configProtectionProvider="DataProtectionConfigurationProvider"> 
      <EncryptedData>
        <CipherData>
    <CipherValue>AQAAANCMnd8BFdERjHoAwE/Cl+sBAAAAexuIJ/8oFE+sGTs7jBKZdgQAAAACAAAAAAADZgAAqAAAABAAAAA
    Kms84dyaCPAeaSC1dIMIBAAAAAASAAACgAAAAEAAAAKaVI6aAOFdqhdc6w1Er3HMwAAAAcZ00MZOz1dI7kYRvkMIn/
    BmfrvoHNUwz6H9rcxJ6Ow41E3hwHLbh79IUWiiNp0VqFAAAAF2sXCdb3fcKkgnagkHkILqteTXh</CipherValue>
        </CipherData>
      </EncryptedData>
    </connectionStrings>

    • Add the following Default.aspx Web page to your application's virtual directory, and then browse to this page to verify that encryption/decryption worked correctly (MyLocalSQLServer is the name of the connection string that you previously specified in the config file)
    <%@ Page Language="C#" %>
    <script runat="server">
        protected void Page_Load(object sender, EventArgs e)
        {
            Response.Write("Clear text connection string is: " + 
                     ConfigurationManager.ConnectionStrings
                                ["MyLocalSQLServer"].ConnectionString);
        }
    </script>
    <html>
      <body/>
    </html>

    Note   For information on where the user key is stored, Windows Data Protection at http://msdn.microsoft.com/en-us/library/ms995355.aspx


    Thanks, AT

    Thursday, May 2, 2013 12:42 PM

All replies

  • Tuesday, April 23, 2013 10:52 PM
  • Hi MARV102,

    From your description, I ‘d like to move this post to  the most related forum.There are more  experts in this aspect, so you will get  better support and  may have more luck getting answers.

    Thanks for your understanding.

    Regards,


    Lisa Zhu [MSFT]
    MSDN Community Support | Feedback to us
    Develop and promote your apps in Windows Store
    Please remember to mark the replies as answers if they help and unmark them if they provide no help.

    Thursday, April 25, 2013 5:05 AM
  • Hi Marv,

    Here is a way to encrypt the config:

    1. Make a tool with above code.

    To encrypt the config file, you only need the following code in this tool:

    section.SectionInformation.ProtectSection(
    "DataProtectionConfigurationProvider");
    
    // Save the current configuration.
    config.Save();

    2. Copy the original config file to the target machine.

    3. Run this tool on the target machine and the unecrypted config file.

    4. Keep the encrypted config file on the target machine, and remove the original one.

    I hope this is clear.

    Best regards,


    Mike Feng
    MSDN Community Support | Feedback to us
    Develop and promote your apps in Windows Store
    Please remember to mark the replies as answers if they help and unmark them if they provide no help.

    Thursday, April 25, 2013 8:30 AM
    Moderator
  • You can have a much better approach for encryption sections in config files using: Windows Data Protection application programming interface (DPAPI).

    DPAPI protected configuration provider and the Aspnet_regiis.exe tool can be used to encrypt sections of configuration files. The DPAPI protected configuration provider supports machine-level and user-level stores for key storage.

    Configuration sections that usually contain sensitive information that you need to encrypt are the following:

    • <appSettings>. This section contains custom application settings
    • <connectionStrings>. This section contains connection strings
    • <identity>. This section can contain impersonation credentials
    • <sessionState>. The section contains the connection string for the out-of-process session state provider

    To encrypt the connectionStrings section in Web.config:

    • Create a new Web site, directory to be configured as a virtual directory
    • Add a configuration file (ex. web.config) to this directory
    • Add connectionString similar to the following example
    <connectionStrings>
      <add name="MyLocalSQLServer" 
           connectionString="Initial Catalog=aspnetdb;
           data source=localhost;Integrated Security=SSPI;" 
           providerName="System.Data.SqlClient"/>
    </connectionStrings>

    • To encrypt the connectionStrings section, run the following command from a .NET command prompt (where MachineDPAPI is the name of the IIS virtual directory):

    aspnet_regiis -pe "connectionStrings" -app "/MachineDPAPI" -prov "DataProtectionConfigurationProvider"

    v  The Aspnet_regiis.exe utility tool is located in the following directory: %WinDir%\Microsoft.NET\Framework\<versionNumber>

    v  The DPAPI machine key is stored at the following location: %windir%\system32\Microsoft\Protect\S-1-5-18

    • Your modified configuration file, with the connectionStrings section encrypted, will look like below example:
    <connectionStrings configProtectionProvider="DataProtectionConfigurationProvider"> 
      <EncryptedData>
        <CipherData>
    <CipherValue>AQAAANCMnd8BFdERjHoAwE/Cl+sBAAAAexuIJ/8oFE+sGTs7jBKZdgQAAAACAAAAAAADZgAAqAAAABAAAAA
    Kms84dyaCPAeaSC1dIMIBAAAAAASAAACgAAAAEAAAAKaVI6aAOFdqhdc6w1Er3HMwAAAAcZ00MZOz1dI7kYRvkMIn/
    BmfrvoHNUwz6H9rcxJ6Ow41E3hwHLbh79IUWiiNp0VqFAAAAF2sXCdb3fcKkgnagkHkILqteTXh</CipherValue>
        </CipherData>
      </EncryptedData>
    </connectionStrings>

    • Add the following Default.aspx Web page to your application's virtual directory, and then browse to this page to verify that encryption/decryption worked correctly (MyLocalSQLServer is the name of the connection string that you previously specified in the config file)
    <%@ Page Language="C#" %>
    <script runat="server">
        protected void Page_Load(object sender, EventArgs e)
        {
            Response.Write("Clear text connection string is: " + 
                     ConfigurationManager.ConnectionStrings
                                ["MyLocalSQLServer"].ConnectionString);
        }
    </script>
    <html>
      <body/>
    </html>

    Note   For information on where the user key is stored, Windows Data Protection at http://msdn.microsoft.com/en-us/library/ms995355.aspx


    Thanks, AT

    Thursday, May 2, 2013 12:42 PM