locked
Encrypting the app.config file RRS feed

  • Question

  • My application will use the DataProtectionConfigurationProvider to encrypt my app.config file. I can encrypt the file from within my applicaiton, but I would like to be able to encrypt it outside the application so that the file is encrypted when it is deployed. I know that you can encrypt web.config files with aspnet_regiis.exe. Is there a tool that can encrypt app.config files as well?

    Eric
    Wednesday, January 18, 2006 3:45 PM

Answers

  • No there is currently no tool available to encrypt your app.config automagically...well at least to my knowledge so don't quote me on that.

    The difference between app.config for desktop apps and web.config for web apps is simple. ASP.net knows what key it uses to encrypt your web.config file and can tell it to the ASP.net application.

    There is no similar service for winform/console applications because they run within their own process.

    It is possible to create your own EncryptedConfigurationProvider and simple application that, given a key, encrypts any file (including app.config). Of course your application will have to provide that key to the ECP in order for it to work. Finally, do not forget that all of the encryption is for naught if you don't hide the key in your assembly. Use a code obfuscator (like dotfuscator) to help you with that.

    Wednesday, January 18, 2006 4:04 PM

All replies

  • No there is currently no tool available to encrypt your app.config automagically...well at least to my knowledge so don't quote me on that.

    The difference between app.config for desktop apps and web.config for web apps is simple. ASP.net knows what key it uses to encrypt your web.config file and can tell it to the ASP.net application.

    There is no similar service for winform/console applications because they run within their own process.

    It is possible to create your own EncryptedConfigurationProvider and simple application that, given a key, encrypts any file (including app.config). Of course your application will have to provide that key to the ECP in order for it to work. Finally, do not forget that all of the encryption is for naught if you don't hide the key in your assembly. Use a code obfuscator (like dotfuscator) to help you with that.

    Wednesday, January 18, 2006 4:04 PM
  • No, can't encrypt the app.config. No that's not right, you can but then your app won't read it

    You can encrypt the values in it and when you read it, just decrypt it. I use this for the connection string for example, so users don't grap the username and password for the DB.
    Wednesday, January 18, 2006 4:30 PM
  • Your right that you can't encrypt the entire file, but using the System.Configuration.SectionInformation.ProtectSection method, you can encrypt entire sections. (new in 2.0 framework) The protect section method only works on sections of that applications config file. I'm looking for a tool that will protect sections of a different application's config file. And of coarse, I want the main application to be able to read them using the framework APIs, the tools encrption needs to be the same as the ProtectSection's encryption.
    Wednesday, January 18, 2006 4:39 PM
  • Then you just need to decompile the program and look at the encryption method. Are code obfuscator good ? Would it be farely easy to find the encryption method when to code of obfuscated ?
    Wednesday, January 18, 2006 9:06 PM
  •  ThE_lOtUs wrote:
    Then you just need to decompile the program and look at the encryption method. Are code obfuscator good ? Would it be farely easy to find the encryption method when to code of obfuscated ?

    Nothing is perfect but obfuscation is about the best that can be done to deter casual cracking.

    Well there is one other way. You can store the key in a database and use SSPI to enable users who are authorized to use the application to retrieve the key (well through the program of course). When the key comes in from the database, the application can use it to decrypt the app.config file. Again, I'd recommend using obfuscation still so that a casual cracker can't determine what is being done.

    Thursday, January 19, 2006 3:21 PM
  • I've written a small command line app that can protect and unprotect sections in your config file. See http://hades.dyndns.ws/blog/index.php?blog=5&p=29&more=1&page=1
    Saturday, February 4, 2006 5:49 PM
  • Take a look at this: http://msdn.microsoft.com/library/default.asp?url=/library/en-us/dnpag2/html/EntLib2.asp  

    The standards and pratices team has some cool examples in their Enterprise Framework. It's asp.net based but its still a pretty good example. I remember that in the 1.x versions they had a nice interface (ment to be customized) to encrypt various configuration settings. 

    Monday, February 6, 2006 11:11 AM
  • Hi  P.J.,

    I've read your post in the group and I'm also searching to encrypt some connection strings in a app.config-file.   Can you send me an example of your code that manages this issue.

    Thanks in advance,
    Marc.
    marcmylle@hotmail.com.donotspam
    Tuesday, February 14, 2006 1:45 PM
  • Hi there PJ

    I'm currently looking for ways to encrypt values of my app.config (DB connection string).

    I've looked at PNG but would like a simpler way to do things.  Can you give an example of your encryption/decryption method?

    brgds
    Tuesday, February 21, 2006 11:04 AM
  • I can't access the site, looks like something i would be interested in ....

     

    Thanks

    Kalpana

    Tuesday, July 31, 2007 1:39 AM
  • Hey zephyr_at_hades,

    Is your sample code still available at http://hades.dyndns.ws/blog/index.php?blog=5&p=29&more=1&page=1
    ?  I cannot browse the link

     

    Thanks,

     

    Monday, August 6, 2007 3:56 PM
  • This is exactly what I am looking for and is the only thing holding me back from deploying my project.  Does anyone have a code sample of not only how to encrypt/decrypt the connections strings in the app.config file, but how to use that functionality in a small application?

    Thanks!
    Monday, February 11, 2008 1:02 PM
  • I forgot to post the code for this some time ago for those who are still looking:

    I created an Installer class for my Setup & Deployment Project.  Then I added a Custom Action to my Setup project to the Install folder (right click on the setup project, choose View Custom Actions.  Then right click on the Install folder and choose Add Custom Action).  Now, add the Primary output for your project.  After you have added the Primary output to the Install folder click on it and goto the Properties window.  In the "CustomActionData" property, add the following text:

    /sectionName="connectionStrings" /provName="DPAPIProtection"

    We are encrypting the ConnectionString section of the app.config file using .NET DPAPIProtection encryption.


    In the Installer class override the Install function and add the following code:

    Code Snippet

    public override void Install(System.Collections.IDictionary stateSaver)
            {
                base.Install(stateSaver);

                //get Configuration section
                //name from custom action parameter
                string sectionName = this.Context.Parameters["sectionName"];

                //get Protected Configuration Provider
                //name from custom action parameter
                string provName = this.Context.Parameters["provName"];

                // get the exe path from the default context parameters
                string exeFilePath = this.Context.Parameters["assemblypath"];

                //encrypt the configuration section
                ProtectSection(sectionName, provName, exeFilePath);


      // Create the DSN --- this is where you could create a DSN for the

      // application.  I call a function in my own DLL.

                string attributes = "DSN=myDSN\0" +
                    "Description=Development DSN\0" +
                    "Server=myServer\0\0";
                DSNConfiguration.SystemDSN.CreateOracleDSN(attributes);
            }

            private void ProtectSection(string sectionName,
                         string provName, string exeFilePath)
            {

    Configuration config =     ConfigurationManager.OpenExeConfiguration(exeFilePath);

              ConfigurationSection section = config.GetSection(sectionName);

                if (!section.SectionInformation.IsProtected)
                {
                    //Protecting the specified section with the specified provider
                    section.SectionInformation.ProtectSection(provName);
                }
                section.SectionInformation.ForceSave = true;
                config.Save(ConfigurationSaveMode.Modified);
            }





    • Proposed as answer by JobaDiniz Thursday, May 28, 2009 12:59 PM
    Monday, March 31, 2008 12:15 PM
  • if you have installed Microsoft Enterprise Library, you can easily encrypt/decrypt using its tool as mentioned in this link

    http://davidhayden.com/blog/dave/archive/2006/01/23/2744.aspx

    http://davidhayden.com/blog/dave/archive/2006/03/02/2870.aspx

     

    Also, after the installation, open the project in studio and right click on the web.config or app.config and you will see the option for the configuration though Enterprise Library.  This option is available in Visual Studio 2005 but I cannot see this in Visual Studio 2008 yet.  Not sure whether its not compatible with 2008 or I have to follow some installation sequences. I will let you guys know if I come across with any solutions.

     

    This is the link which explains how to work with encryption within studio http://www.pnpguidance.net/Post/EnterpriseLibrary3VisualStudioIntegratedConfigurationEditor.aspx .  Read, read & read...

     

    Keep in mind that once you open the .config file you have luxuary of ecrypting each pieces/blocks seperately.  Thats the beatuy of it.

     

    For your information I am using Enterprise Library 3.1 which is the latest version and has tonnes of tools that makes your life a breeze.  You can download this library at http://msdn2.microsoft.com/en-us/library/aa480453.aspx.  Also, look forward for 4.0 at http://www.codeplex.com/entlib

     

    -Happy coding

    -Vincent

     

     

    • Proposed as answer by TomTom1234 Thursday, April 2, 2009 10:24 AM
    Tuesday, April 1, 2008 12:08 AM
  • Thank you vpdsouza so much!! you just made my day. I wanted to give you a medal if I could...... MS did a great job to protect configuration data in such an easy and efficient way!!
    Tuesday, May 12, 2009 2:28 PM
  • This link helped me out tremendously with easily encrypting an app.config file: http://www.dotnetprofessional.com/blog/post/2008/03/03/Encrypt-sections-of-WebConfig-or-AppConfig.aspx

    Basically rename the app.config to web.config, use aspnet_regiis.exe to encrypt the file, rename the file back to app.config.

    It worked for me without writing a single line of code (if you don't count editing the batch file).

    Tuesday, June 9, 2009 7:53 PM
  • thank you for the post - what about clik once deployment? I can encrypt and dycript  and read the data in my app.config file but once the application is deployed the users get an error - Failed to decrypt using provider RsaProtectedConfigurationProvider'. Error message from the provider:  The RSA key container could not be opened.  This looks like i am supposed to export/import the key container in some fashion but no matter how long I looked i could not find the naswer anywhere. Any pointers?

    I use this code to encrypt the data:

     

    public static string ProtectConfiguration(string SectionName, string FileName)

    {

     

    StringBuilder Response = new StringBuilder();

     

    try

    {

     

    ExeConfigurationFileMap fileMap = new ExeConfigurationFileMap();

    fileMap.ExeConfigFilename = FileName;

     

    // Get the application configuration file.

     

    Configuration config = ConfigurationManager.OpenMappedExeConfiguration(fileMap, ConfigurationUserLevel.None);

     

     

    // Get the section to protect.

     

     

    ConfigurationSection configSection = config.GetSection(SectionName);

     

     

    // Define the Rsa provider name.

     

    string provider =

     

    "RsaProtectedConfigurationProvider";

     

     

    if (configSection != null)

    {

     

    if (!configSection.SectionInformation.IsProtected)

    {

     

    if (!configSection.ElementInformation.IsLocked)

    {

     

    // Protect the section.

    configSection.SectionInformation.ProtectSection(provider);

    configSection.SectionInformation.ForceSave =

    true;

    config.Save(

    ConfigurationSaveMode.Full);

    Response.Append(

    String.Format("Section {0} is now protected by {1}",

    configSection.SectionInformation.Name,

    configSection.SectionInformation.ProtectionProvider.Name));

    }

     

    else

    Response.Append(

    String.Format(

     

    "Can't protect, section {0} is locked",

    configSection.SectionInformation.Name));

    }

     

    else

    Response.Append(

    String.Format(

     

    "Section {0} is already protected by {1}",

    configSection.SectionInformation.Name,

    configSection.SectionInformation.ProtectionProvider.Name));

    }

     

    else

    Response.Append(

    String.Format("Can't get the section {0}",

    SectionName));

    }

     

    catch (Exception ex)

    {

    Response.Append(ex.ToString());

    }

     

    return Response.ToString();

    }

    then this will read the data:

     

    public static void GetCreditCardsProviderCredentialsFromAppConfig(string SectionName, string FileName)

    {

     

    try

    {

     

    ExeConfigurationFileMap fileMap = new ExeConfigurationFileMap();

    fileMap.ExeConfigFilename = FileName;

     

    Configuration config = ConfigurationManager.OpenMappedExeConfiguration(fileMap, ConfigurationUserLevel.None);

     

    ConfigurationSection section = config.GetSection(SectionName);

     

    string xml = section.SectionInformation.GetRawXml(); //this is the place the code breaks when deployed

     

    using (XmlReader reader = XmlReader.Create(new StringReader(xml)))

    {

     

    while (reader.Read())

    {

    reader.ReadToFollowing(

    "add");

     

    if (reader.GetAttribute("key") == "username")

    {

    _creditcardsProviderCredentialsUserName = reader.GetAttribute(

    "value");

    }

     

     

    else if (reader.GetAttribute("key") == "password")

    {

    _creditcardsProviderCredentialsPassword = reader.GetAttribute(

    "value");

    }

     

     

    else if (reader.GetAttribute("key") == "provider")

    {

     

    _creditcardsProviderCredentialsProviderName = reader.GetAttribute(

    "value");

    }

     

    else { reader.ReadToFollowing("add"); }

    }

    }

    }

     

     

    catch (Exception ex)

    {

     

    MessageBox.Show("Credit card service provider credentials cannot be read - " + ex.Message,

     

    "Contact your administrator!",

     

    MessageBoxButtons.OK,

     

    MessageBoxIcon.Error);

    }

     

    }



    Thanks!
    dot net developer
    Thursday, July 16, 2009 10:01 PM
  • this is very nice, but how did your users access the application? Can anybody else but you decrypt the data?
    dot net developer
    Thursday, July 16, 2009 10:06 PM