how can i encrypt app.config when deploying a windows forms app?

James Foy 25 Reputation points
2023-08-16T15:45:10.18+00:00

The app.config file is plain language and contains passwords for data connection strings. How can I encrypt it for deployment?

Windows Forms
Windows Forms
A set of .NET Framework managed libraries for developing graphical user interfaces.
1,927 questions
.NET
.NET
Microsoft Technologies based on the .NET software framework.
4,103 questions
{count} votes

2 answers

Sort by: Most helpful
  1. Jiale Xue - MSFT 49,831 Reputation points Microsoft External Staff
    2023-08-17T03:13:26.1733333+00:00

    Hi @James Foy ,Welcome to Microsoft Q&A,

    Regarding encrypted strings, a low-cost way is to use the AES symmetric encryption algorithm, and then use a secure method to generate a key.

    You could use a cryptographically secure pseudo-random number generator to generate a random key. Keys should be strong enough to resist cracking and brute force attacks.

    Regardless of the encryption method you use, what matters is how you plan to store the keys.

    About the AES key. You can generate a key before deployment and manually enter the key when deploying.

    It is also possible if you choose to accept the key from the server.

    If you deploy directly on the machine, you can also use DPAPI encryption, but the encryption key is computer-level.

    KEY is not required at runtime.

    Best Regards,

    Jiale


    If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment". 

    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

    0 comments No comments

  2. Karen Payne MVP 35,561 Reputation points
    2023-08-17T07:51:07.96+00:00

    Use the following

    using System;
    using System.Configuration;
    using System.IO;
    
    namespace ExampleProject.Classes
    {
    
        public class ConnectionProtection
        {
            public string FileName { get; set; }
            /// <summary>
            /// Determine if configuration file exists for application
            /// </summary>
            /// <param name="fileName">Current executable and path</param>
            public ConnectionProtection(string fileName)
            {
                if (!File.Exists(string.Concat(fileName, ".config")))
                {
                    throw new FileNotFoundException(string.Concat(fileName, ".config"));
                }
                FileName = fileName;
            }
            /// <summary>
            /// Encrypt ConnectionString
            /// </summary>
            /// <param name="encrypt"></param>
            /// <param name="fileName"></param>
            /// <returns></returns>
            private bool EncryptConnectionString(bool encrypt, string fileName)
            {
                bool success = true;
                Configuration configuration = null;
    
                try
                {
                    configuration = ConfigurationManager.OpenExeConfiguration(fileName);
                    var configSection = (ConnectionStringsSection)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 ex)
                {
                    success = false;
                }
    
                return success;
    
            }
            public bool IsProtected()
            {
                Configuration configuration = ConfigurationManager.OpenExeConfiguration(FileName);
                var configSection = (ConnectionStringsSection)configuration.GetSection("connectionStrings");
                return configSection.SectionInformation.IsProtected;
            }
            public bool EncryptFile()
            {
                if (File.Exists(FileName))
                {
                    return EncryptConnectionString(true, FileName);
                }
                else
                {
                    return false;
                }
            }
            public bool DecryptFile()
            {
                if (File.Exists(FileName))
                {
                    return EncryptConnectionString(false, FileName);
                }
                else
                {
                    return false;
                }
            }
        }
    
    }
    

    Usage

    namespace ExampleProject
    {
        public partial class Form1 : Form
        {
            private readonly ConnectionProtection _protection = 
                new ConnectionProtection(AppDomain.CurrentDomain.BaseDirectory);
    
            public Form1()
            {
                InitializeComponent();
                if (!_protection.IsProtected())
                {
                    _protection.EncryptFile();
                }
            }
    
            private void button1_Click(object sender, EventArgs e)
            {
                _protection.DecryptFile();
                try
                {
                    // do database work
                }
                finally
                {
                    _protection.EncryptFile();
                }
                
            }
        }
    }
    
    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.