Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • Home
  • SEARCH
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 3751230
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 19, 20262026-05-19T09:02:42+00:00 2026-05-19T09:02:42+00:00

I want to create a msbuild task which encrypts certain sections of my web.configs.

  • 0

I want to create a msbuild task which encrypts certain sections of my web.configs. The following code works great inside a weapplication. Running the code as an msbuild causes an error saying it cannot create the config file..

System.Configuration.Configuration config = WebConfigurationManager.OpenWebConfiguration(Request.ApplicationPath);
ConfigurationSection section = config.GetSection(sectionName);

if (section != null && !section.SectionInformation.IsProtected)
{
    section.SectionInformation.ProtectSection(provider);
    config.Save();
}

I couldn’t find any classes which do the right job. Ideas anyone?

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-19T09:02:42+00:00Added an answer on May 19, 2026 at 9:02 am

    You should create your own custom MSBuild task.

    The below code is a custom task.

    I’ve made mine application(winforms) capable, but I marked the lines you can change for web based.

    I’ve created an abstract class with 2 subclasses to handle encrypt and decryption.

    Cheers!

    namespace MyCompany.MSBuild.Tasks.Security
    {
    
        using System;
        using System.Linq;
        using System.Diagnostics;
        using System.Configuration;
        //using System.Web.Configuration;
    
        using Microsoft.Build.Framework;
        using Microsoft.Build.Utilities;
    
        public abstract class ConfigurationProtectorBaseTask : Task
        {
            private static readonly string RSA_PROVIDER = "RSAProtectedConfigurationProvider";
            private static readonly string DATA_PROTECTION_PROVIDER = "DataProtectionConfigurationProvider";
    
            /// <summary>
            /// Gets or sets the ExePath.  This would be the name of the .exe (or .dll) which has a corresponding .config associated with it.
            /// </summary>
            /// <value>The ExePath.</value>
            [Required]
            public string ExePath { get; set; }
    
            /// <summary>
            /// Gets or sets the SectionName of the configuration file you are trying to encrypt.
            /// </summary>
            /// <value>The SectionName.</value>
            [Required]
            public string SectionName { get; set; }
    
            /// <summary>
            /// Gets or sets the Provider.
            /// </summary>
            /// <value>The Provider.</value>
            [Required]
            public string Provider { get; set; }
    
            /// <summary>
            /// Task Entry Point.
            /// </summary>
            /// <returns></returns>
            public override bool Execute()
            {
                if (!String.IsNullOrEmpty(this.Provider))
                {
                    if (String.Equals(this.Provider, DATA_PROTECTION_PROVIDER, StringComparison.OrdinalIgnoreCase) || String.Equals(this.Provider, RSA_PROVIDER, StringComparison.OrdinalIgnoreCase))
                    { }
                    else
                    {
                        Log.LogWarning(string.Format("Provider must be either '{0}' or '{1}'. Your value was '{2}'.", DATA_PROTECTION_PROVIDER, RSA_PROVIDER, this.Provider));
                        return false;
                    }
                }
    
                if (!String.IsNullOrEmpty(this.ExePath))
                {
                    Log.LogCommandLine(string.Format("{0}", this.ExePath));
                    Console.WriteLine(this.ExePath);
                }
    
                InternalExecute();
                return !Log.HasLoggedErrors;
            }
    
            protected abstract void InternalExecute();
    
            protected Configuration GetConfiguration()
            {
                //WebVersion
                //Configuration config = WebConfigurationManager.OpenWebConfiguration(this.ApplicationPath);
    
                //NonAspNet version
                Configuration config = ConfigurationManager.OpenExeConfiguration(ExePath);
    
                return config;
            }
    
        }
    }
    
    
    
    
    namespace MyCompany.MSBuild.Tasks.Security
    {
        using System;
        using System.Linq;
        using System.Diagnostics;
        using System.Configuration;
        using System.Web.Configuration;
    
        using Microsoft.Build.Framework;
        using Microsoft.Build.Utilities;
    
        public class ConfigurationProtectorEncrypterTask : ConfigurationProtectorBaseTask 
        {
    
            /// <summary>
            /// Internal Execute Wrapper.
            /// </summary>
            protected override void InternalExecute()
            {
                Configuration config = base.GetConfiguration();
                ConfigurationSection section = config.GetSection(this.SectionName);
                if (section != null && !section.SectionInformation.IsProtected)
                {
                    section.SectionInformation.ProtectSection(this.Provider);
                    config.Save();
                }
            }
    
        }
    }
    
    
    
    
    
    
    
    
    
    namespace MyCompany.MSBuild.Tasks.Security
    {
        using System;
        using System.Linq;
        using System.Diagnostics;
        using System.Configuration;
        using System.Web.Configuration;
    
        using Microsoft.Build.Framework;
        using Microsoft.Build.Utilities;
    
        public class ConfigurationProtectorDecrypterTask : ConfigurationProtectorBaseTask
        {
    
            /// <summary>
            /// Internal Execute Wrapper.
            /// </summary>
            protected override void InternalExecute()
            {
                Configuration config = base.GetConfiguration();
                ConfigurationSection section = config.GetSection(this.SectionName);
                if (section != null && section.SectionInformation.IsProtected)
                {
                    section.SectionInformation.UnprotectSection();
                    config.Save();
                }
            }
    
        }
    }
    
    
    
    
    
    
    
    
    
    ::::Save this as: ConfigurationProtectorTaskTest.msbuild 
    
    <?xml version="1.0" encoding="utf-8"?>
    <Project DefaultTargets="AllTargetsWrapper" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
    
      <UsingTask AssemblyFile="MyCompany.MSBuild.dll" TaskName="ConfigurationProtectorEncrypterTask"/>
      <UsingTask AssemblyFile="MyCompany.MSBuild.dll" TaskName="ConfigurationProtectorDecrypterTask"/>
    
    
      <Target Name="AllTargetsWrapper">
        <CallTarget Targets="ConfigurationProtectorEncrypterTask1" />
        <CallTarget Targets="ConfigurationProtectorDecrypterTask2" />
      </Target>
    
    
      <PropertyGroup>
        <MyExePath>C:\SomeFolder\MyCompany.SomeExe.exe</MyExePath>
        <MySectionName>connectionStrings</MySectionName>
        <MyProvider>RSAProtectedConfigurationProvider</MyProvider>
      </PropertyGroup>
    
    
    
      <Target Name="ConfigurationProtectorEncrypterTask1">
        <ConfigurationProtectorEncrypterTask ExePath="$(MyExePath)" SectionName="$(MySectionName)" Provider="$(MyProvider)">
        </ConfigurationProtectorEncrypterTask>
      </Target>
    
    
      <Target Name="ConfigurationProtectorDecrypterTask2">
        <ConfigurationProtectorDecrypterTask ExePath="$(MyExePath)" SectionName="$(MySectionName)" Provider="$(MyProvider)">
        </ConfigurationProtectorDecrypterTask>
    
      </Target>
    
    
    
    </Project>
    
    
    
    
    
    :REM BAT FILE TO CALL THE ABOVE .msbuild file
    
    call "%VS90COMNTOOLS%\vsvars32.bat"
    del *.log
    msbuild /target:ConfigurationProtectorEncrypterTask1 ConfigurationProtectorTaskTest.msbuild /l:FileLogger,Microsoft.Build.Engine;logfile=ConfigurationProtectorEncrypterTask1.log
    msbuild /target:ConfigurationProtectorDecrypterTask2 ConfigurationProtectorTaskTest.msbuild /l:FileLogger,Microsoft.Build.Engine;logfile=ConfigurationProtectorDecrypterTask2.log
    

    This will help as well:
    http://www.codeproject.com/KB/dotnet/EncryptingTheAppConfig.aspx
    http://www.beansoftware.com/ASP.NET-Tutorials/Encrypting-Connection-String.aspx

    But the encapsulation into a MSBuild Task is my contribution.

    The second URL above also mentions a command line method:

    Here is that quoted material (partial quote that is):::

    Encryption/Decryption using aspnet_regiis.exe command line tool

    You can also encrypt and decrypt sections in the Web.config file using the aspnet_regiis.exe command-line tool, which can be found in the \Microsoft.Net\Framework\version directory. To encrypt a section of the Web.config using the DPAPI machine key with this command-line tool, use following command.

    aspnet_regiis.exe -pe “connectionStrings” -app “/YourWebSiteName” –prov “DataProtectionConfigurationProvider”

    To decrypt connectionStrings section using this tool, you can specify following command in aspnet_iisreg.exe tool.

    aspnet_regiis.exe -pd “connectionStrings” -app “/YouWebSiteName”

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I want to create a custom MSBuild task that changes my .cs files before
I want to create an allocator which provides memory with the following attributes: cannot
I want to create a client side mail creator web page. I know the
I want create a drop shadow around the canvas component in flex. Technically speaking
I want to create a Java application bundle for Mac without using Mac. According
I want to create a function that performs a function passed by parameter on
I want to create a simple http proxy server that does some very basic
I want to create a draggable and resizable window in JavaScript for cross browser
I want to create my Rails application with MySQL, because I like it so
I want to create a number of masked edit extenders from codebehind. Something like:

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.