none
How to protect App.config and Web.config files? RRS feed

  • Question

  • Hi, I'm implementing a software system in C#, which contains two services and a web application. For the first ones I'm using ServiceBase and for the last one I'm using ASP.NET MVC framework. I've create three different solution, and for the services I have App.config file and for the web app I have Web.config file.

    Each file contains some important informations that I don't want to show to the users that will use this system.

    Each files contains <connectionStrings> sub-section and <appSettings> sub-section. I want to protect/encrypt those sections. How I can do that? 

    Thursday, October 24, 2019 7:55 AM

Answers

  • Hi thereisnopatchforhumancruelty,

    Thank you for posting here.

    You can refer to the following link to encrypt your configuration file.

    Protecting Connection Strings and Other Configuration Information (C#)

    Encrypting Configuration Information in ASP.NET 2.0 Applications

    Encrypting ASP.NET Application Settings

    Note: This response contains a reference to a third party World Wide Web site. Microsoft is providing this information as a convenience to you. Microsoft does not control these sites and has not tested any software or information found on these sites; Therefore, Microsoft cannot make any representations regarding the quality, safety, or suitability of any software or information found there. There are inherent dangers in the use of any software found on the Internet, and Microsoft cautions you to make sure that you completely understand the risk before retrieving any software from the Internet.

    Hope this could help you.

    Best regards,
    Timon


    MSDN Community Support
    Please remember to click "Mark as Answer" the responses that resolved your issue, and to click "Unmark as Answer" if not. This can be beneficial to other community members reading this thread. If you have any compliments or complaints to MSDN Support, feel free to contact MSDNFSF@microsoft.com.

    Friday, October 25, 2019 7:50 AM

All replies

  • Have you looked the built-in encryption of configuration files? I have not used it besides some samples, but that might help.

    Encrypting Configuration Information Using Protected Configuration

    Thursday, October 24, 2019 8:17 AM
  • For app.config,

    Add a reference to System.Configuration, add the following class.

    using System;
    using System.Configuration;
    using System.IO;
    
    namespace ConfigurationLibrary 
    {
        public class ConnectionProtection
        {
            public string FileName { get; set; }
            public ConnectionProtection(string ExecutableFileName)
            {
                if (!(File.Exists(string.Concat(ExecutableFileName, ".config"))))
                {
                    throw new FileNotFoundException(string.Concat(ExecutableFileName, ".config"));
                }
                FileName = ExecutableFileName;
            }
            private bool EncryptConnectionString(bool encrypt, string fileName)
            {
                bool success = true;
                Configuration configuration = null;
    
                try
                {
                    configuration = ConfigurationManager.OpenExeConfiguration(fileName);
                    var configSection = configuration.GetSection("connectionStrings") as ConnectionStringsSection;
    
                    if ((!configSection.ElementInformation.IsLocked) && (!configSection.SectionInformation.IsLocked))
                    {
                        if (encrypt && (!configSection.SectionInformation.IsProtected))
                        {
                            // encrypt the file
                            configSection.SectionInformation.ProtectSection("DataProtectionConfigurationProvider");
                        }
    
                        if ((!encrypt) && configSection.SectionInformation.IsProtected) //encrypt is true so encrypt
                        {
                            // decrypt the file. 
                            configSection.SectionInformation.UnprotectSection();
                        }
    
                        configSection.SectionInformation.ForceSave = true;
                        configuration.Save();
    
                        success = true;
    
                    }
                }
                catch (Exception)
                {
                    success = false;
                }
    
                return success;
    
            }
            public bool IsProtected()
            {
                var configuration = ConfigurationManager.OpenExeConfiguration(FileName);
                var configSection = configuration.GetSection("connectionStrings") as ConnectionStringsSection;
                return configSection.SectionInformation.IsProtected;
            }
            public bool EncryptFile() => File.Exists(FileName) && EncryptConnectionString(true, FileName);
    
            public bool DecryptFile() => File.Exists(FileName) && EncryptConnectionString(false, FileName);
        }
    }
    

    In the startup class create an instance of the class above

    ConnectionProtection operations = 
    	new ConnectionProtection(Application.ExecutablePath);
    

    Or

    ConnectionProtection operations =
        new ConnectionProtection(Assembly.GetEntryAssembly().Location);

    First time encrypt the config file

    operations.EncryptFile();

    To access a connection first decrypt 

    operations.DecryptFile();

    Get the connection string then encrypt again.

    operations.EncryptFile();

    Concerning web config, see the following.

    https://www.codeproject.com/Tips/795135/Encrypt-ConnectionString-in-Web-Config


    Please remember to mark the replies as answers if they help and unmarked them if they provide no help, this will help others who are looking for solutions to the same or similar problem. Contact via my Twitter (Karen Payne) or Facebook (Karen Payne) via my MSDN profile but will not answer coding question on either.

    NuGet BaseConnectionLibrary for database connections.

    StackOverFlow
    profile for Karen Payne on Stack Exchange

    Thursday, October 24, 2019 10:20 AM
    Moderator
  • For app.config,

    Add a reference to System.Configuration, add the following class.

    using System;
    using System.Configuration;
    using System.IO;
    
    namespace ConfigurationLibrary 
    {
        public class ConnectionProtection
        {
            public string FileName { get; set; }
            public ConnectionProtection(string ExecutableFileName)
            {
                if (!(File.Exists(string.Concat(ExecutableFileName, ".config"))))
                {
                    throw new FileNotFoundException(string.Concat(ExecutableFileName, ".config"));
                }
                FileName = ExecutableFileName;
            }
            private bool EncryptConnectionString(bool encrypt, string fileName)
            {
                bool success = true;
                Configuration configuration = null;
    
                try
                {
                    configuration = ConfigurationManager.OpenExeConfiguration(fileName);
                    var configSection = configuration.GetSection("connectionStrings") as ConnectionStringsSection;
    
                    if ((!configSection.ElementInformation.IsLocked) && (!configSection.SectionInformation.IsLocked))
                    {
                        if (encrypt && (!configSection.SectionInformation.IsProtected))
                        {
                            // encrypt the file
                            configSection.SectionInformation.ProtectSection("DataProtectionConfigurationProvider");
                        }
    
                        if ((!encrypt) && configSection.SectionInformation.IsProtected) //encrypt is true so encrypt
                        {
                            // decrypt the file. 
                            configSection.SectionInformation.UnprotectSection();
                        }
    
                        configSection.SectionInformation.ForceSave = true;
                        configuration.Save();
    
                        success = true;
    
                    }
                }
                catch (Exception)
                {
                    success = false;
                }
    
                return success;
    
            }
            public bool IsProtected()
            {
                var configuration = ConfigurationManager.OpenExeConfiguration(FileName);
                var configSection = configuration.GetSection("connectionStrings") as ConnectionStringsSection;
                return configSection.SectionInformation.IsProtected;
            }
            public bool EncryptFile() => File.Exists(FileName) && EncryptConnectionString(true, FileName);
    
            public bool DecryptFile() => File.Exists(FileName) && EncryptConnectionString(false, FileName);
        }
    }

    In the startup class create an instance of the class above

    ConnectionProtection operations = 
    	new ConnectionProtection(Application.ExecutablePath);

    Or

    ConnectionProtection operations =
        new ConnectionProtection(Assembly.GetEntryAssembly().Location);

    First time encrypt the config file

    operations.EncryptFile();

    To access a connection first decrypt 

    operations.DecryptFile();

    Get the connection string then encrypt again.

    operations.EncryptFile();

    Concerning web config, see the following.

    https://www.codeproject.com/Tips/795135/Encrypt-ConnectionString-in-Web-Config


    Please remember to mark the replies as answers if they help and unmarked them if they provide no help, this will help others who are looking for solutions to the same or similar problem. Contact via my Twitter (Karen Payne) or Facebook (Karen Payne) via my MSDN profile but will not answer coding question on either.

    NuGet BaseConnectionLibrary for database connections.

    StackOverFlow
    profile for Karen Payne on Stack Exchange

    How I can do that for appSettings section too?
    Thursday, October 24, 2019 12:29 PM
  • Hi thereisnopatchforhumancruelty,

    Thank you for posting here.

    You can refer to the following link to encrypt your configuration file.

    Protecting Connection Strings and Other Configuration Information (C#)

    Encrypting Configuration Information in ASP.NET 2.0 Applications

    Encrypting ASP.NET Application Settings

    Note: This response contains a reference to a third party World Wide Web site. Microsoft is providing this information as a convenience to you. Microsoft does not control these sites and has not tested any software or information found on these sites; Therefore, Microsoft cannot make any representations regarding the quality, safety, or suitability of any software or information found there. There are inherent dangers in the use of any software found on the Internet, and Microsoft cautions you to make sure that you completely understand the risk before retrieving any software from the Internet.

    Hope this could help you.

    Best regards,
    Timon


    MSDN Community Support
    Please remember to click "Mark as Answer" the responses that resolved your issue, and to click "Unmark as Answer" if not. This can be beneficial to other community members reading this thread. If you have any compliments or complaints to MSDN Support, feel free to contact MSDNFSF@microsoft.com.

    Friday, October 25, 2019 7:50 AM
  • Hi thereisnopatchforhumancruelty,

    Thank you for posting here.

    You can refer to the following link to encrypt your configuration file.

    Protecting Connection Strings and Other Configuration Information (C#)

    Encrypting Configuration Information in ASP.NET 2.0 Applications

    Encrypting ASP.NET Application Settings

    Note: This response contains a reference to a third party World Wide Web site. Microsoft is providing this information as a convenience to you. Microsoft does not control these sites and has not tested any software or information found on these sites; Therefore, Microsoft cannot make any representations regarding the quality, safety, or suitability of any software or information found there. There are inherent dangers in the use of any software found on the Internet, and Microsoft cautions you to make sure that you completely understand the risk before retrieving any software from the Internet.

    Hope this could help you.

    Best regards,
    Timon


    MSDN Community Support
    Please remember to click "Mark as Answer" the responses that resolved your issue, and to click "Unmark as Answer" if not. This can be beneficial to other community members reading this thread. If you have any compliments or complaints to MSDN Support, feel free to contact MSDNFSF@microsoft.com.

    Thank you, I've used aspnet_regiis.exe -pdf or aspnet_regiis.exe -pef for decrypt and encrypt my files. I'll study how to do this in the machines in which my system will be deployed. Thank you so much!
    Tuesday, October 29, 2019 4:16 PM