Encrypt and Decrypt ConnectionString in Web.Config

Encrypting and decrypting config files can be performed programatically using .NET Framework methods or by using the ASP.NET IIS Registration tool (aspnet_regiis.exe). With the encryption commands you can target either the path to the config file or reference an IIS application name. In my examples I will be encrypting and decrypting the connectionStrings section with the .NET Framework 4. I am using Entity Framework in my project so it will have little different format for connectionString value as compared to traditional SQL Server Connection String so don’t get confused 🙂

Before Encrypting Web.Config

If you look at the below Config file, it can be easily readable. This doesn’t seem to be secure if anyone has access to your Web.Config file.


<connectionStrings>
    <add name="DatabaseEntities" connectionString="metadata=res://*/Models.Model.csdl| res://*/Models.Model.ssdl|res://*/Models.Model.msl;provider=System.Data.SqlClient;provider connection string=&quot;data source=(LocalDB)\v11.0;attachdbfilename=|DataDirectory|\EmpDB.mdf;integrated security=True;MultipleActiveResultSets=True;App=EntityFramework&quot;" providerName="System.Data.EntityClient" />
    <add name="EmpDBEntities" connectionString="metadata=res://*/Models.EmpDBModel.csdl| res://*/Models.EmpDBModel.ssdl|res://*/Models.EmpDBModel.msl;provider=System.Data.SqlClient;provider connection string=&quot;data source=(LocalDB)\v11.0;attachdbfilename=|DataDirectory| \EmpDB.mdf;integrated security=True;multipleactiveresultsets=True;application name=EntityFramework&quot;" providerName="System.Data.EntityClient" />
  </connectionStrings>

You will find aspnet_regiis.exe in the C:\Windows\Microsoft.NET\Framework\version\ folder. With the .NET Framework you can use the builtin protected configuration providers  RSAProtectedConfigurationProvider or DPAPIProtectedConfigurationProvider to encrypt and decrypt sections of your config files.

The general syntax to encrypt a config section is as follows:

aspnet_regiis.exe -pef section physical_directory -prov provider
or
aspnet_regiis.exe -pe section -app virtual_directory -prov provider

It is important to note when using aspnet_regiis.exe to encrypt or decrypt config files and you specify a physical path (rather than a web app name) the command is hardcoded for a file named “web.config”.

If you are trying to run the command against an app.config you will first need to rename that file to web.config before running the command. Rename it back afterwards before using it.

For this reason I find it easier to create a .bat file hardcoded with the necessary command syntax to encrypt my configs and then a 2nd .bat file to decrypt my configs.

For the example below I am using the builtin DPAPI provider to encrypt a web.config in “D:\CodePractice\WebAPICRUDwithBootstrap\WebAPICRUDwithBootstrap”. The encrypted web.config is shown below.

Open Visual Studio Command Prompt with Administrator privileges &  Run the following command.


C:\WINDOWS\system32>ASPNET_REGIIS -pef "connectionStrings" "D:\CodePractice\WebAPICRUDwithBootstrap\WebAPICRUDwithBootstrap" -prov "DataProtectionConfigurationProvider"
Microsoft (R) ASP.NET RegIIS version 4.0.30319.0
Administration utility to install and uninstall ASP.NET on the local machine.
Copyright (C) Microsoft Corporation.  All rights reserved.
Encrypting configuration section...
Succeeded!

Note: The parameter “connectionStrings” is case sensitive.

After Encrypting Web.Config

After encrypting your ConnectionStrings section, your ConnectionStrings will not be in a readable format.


<connectionStrings configProtectionProvider="DataProtectionConfigurationProvider">
    <EncryptedData>
      <CipherData>
        <CipherValue>AQAAANCMnd8BFdERjHoAwE/Cl+sBAAAASngQsfmlQUm5xLTzrlz1fQQAAAACAAAAAAAQZgAAAAEAACAAAAB/hV+ondATNHaaHnJRPjZcljgUEaG2WbY8YsXfgylN/QAAAAAOgAAAAAIAACAAAAB/OUXEFeT8LRgHl0vgpAhuDXU6BYXEsSfxSBhivlSlaMAGAACqBxJbXx2//R7w7DVEq+JeeQQJYcrHja8Vth/kqPzXMJuPgxxaGVdm0NuFaUbzd6tFUWMW6vuMyuGhPHvAnbMel7tUe/FthjBGw1fBuS3gDRTNqb4YrUWomWlPW1Nvx11t3gGyCSiTChvBpTzZ2ENU92OHndMVbi2D/8dHJS4fA9tyqXKqVbelwpHn/7jdMPbLjdHSjtcmA5tf/VQNOu8JfuiBIa0UrcUcwiX/UYs3awH+jjMkHlEykT15Nd/vndl1oC8223eQ32GvCLg5DCeXhPzGTNFqZtWRaYiP7A7KOLPksvJIe60OlUt/yylzDufSfgxh6Y8YrWqmWfjKqWuqqqHZr1m8WDun+qLINQXEG++P8nKzrUzkjMxRzrq0kVcmwcMSS4QTdObhJt1NNZaEzy9HNOtfCKCAMYEzedrf0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/87bi3Mi6Vr8CDR6caxToEpp4ruXJ63EXIWaA2Hnp6TXSGt41pHrup12ewLHfa7yT4f2aXRS3QPrC8HJhHH9mxiiyju7ItnjpMx9qYJASgEZjtSzf+lvK6kPgAuLaWgUZCcDF1/PnkaA7qn5bzrYp7Hv3Wz5vkvfAtN63iyxziCn1SN3uHFStR1xx9ulVssQCpuOOpXIzfhtxQWc8Jh2D8NsA13E9iqRVhRkozH1oC7ZhTYkoOg9iyYYmJNHOQdkwN8US9sIYtw5CGUblBT+ZyI54tjQXibDHjxkdxcrDy1i67Hkgo/MvoCFtBRwoBaoEreWdw7+PBkWGxZsa47+OFZ5FrCSsvjePDnwyW1vJT8cE+AcAivFnPNu2k4PDaQEgHV07FbzMCzwTGKt3hyPRinTpKMO+yUlwXUs4YLwV4NOgXrI0jMeyY47502aNbAVFRKgLYRJj8U/flXmt7v9qQ1QQAc73VFjQvCRIe6QGkC4R1ACVJfnMhDFibmqw8eZpOSCmZB2doiOBonaGMWZTehY19LYeyTzUH3hk5Ks8vU77XAEr+bDiggZEivWFUaajVBezy+Vo9fZEOOtJTxj3MIbw4PjaZpR1St7uhl7Y/wxdIsKP6ignTThcmcRTitxHTh8LYQdKQZyS1kgilYY+oVsCvaeNkftWXSBIDPuLNBo899dKNjDS3fJjJnfGux2n8nnSi/bJ+o3F4wlIhrv3+7+1vjKamjGqVty+GJEjdD9SpdjPN22ItXhfq021JW5HFoWl9/HMx+0ZIfqeBbNU4RHoZAAAAAZskzzUob+vaXFjZwZ5m2OtFM2T4wDGb72VioAfQnTqmL4wMA1cYCVhL4ne2K+en8gzenGK1Cfk4FwlDAeu6Etw==</CipherValue>
      </CipherData>
    </EncryptedData>
  </connectionStrings>

Accessing Decrypted Configuration Settings

It’s very good to know that ASP.NET automatically decrypts the contents of the Web.Config file when it processes the file. Therefore, no additional steps are required to decrypt the encrypted configuration settings. You can run your existing application by encrypting your Web.Config file and it will run perfectly without any modification to your existing code.

Decrypting the Connection String

When decrypting a config section you do not need to specify the protected configuration provider. Just like when encrypting a config file we can target either a file path or IIS web application name. Here is the syntax to decrypt a configuration file section:

aspnet_regiis.exe –pdf section physical_directory
or
aspnet_regiis.exe –pd section -app virtual_directory

In my example below I decrypt the connectionStrings section of my web.config in “D:\CodePractice\WebAPICRUDwithBootstrap\WebAPICRUDwithBootstrap”. As a reminder again when using the –pdf option we do not need to specify “web.config” in the syntax.

C:\WINDOWS\system32>aspnet_regiis.exe -pdf "connectionStrings" "D:\CodePractice\WebAPICRUDwithBootstrap\WebAPICRUDwithBootstrap"
Microsoft (R) ASP.NET RegIIS version 4.0.30319.0
Administration utility to install and uninstall ASP.NET on the local machine.
Copyright (C) Microsoft Corporation.  All rights reserved.
Decrypting configuration section...
Succeeded!

After running the above command, the connectionStrings section of the web.config is decrypted as shown below.


 <connectionStrings>
    <add name="DatabaseEntities" connectionString="metadata=res://*/Models.Model.csdl| res://*/Models.Model.ssdl|res://*/Models.Model.msl;provider=System.Data.SqlClient;provider connection string=&quot;data source=(LocalDB)\v11.0;attachdbfilename=|DataDirectory|\EmpDB.mdf;integrated security=True;MultipleActiveResultSets=True;App=EntityFramework&quot;" providerName="System.Data.EntityClient" />
    <add name="EmpDBEntities" connectionString="metadata=res://*/Models.EmpDBModel.csdl| res://*/Models.EmpDBModel.ssdl|res://*/Models.EmpDBModel.msl;provider=System.Data.SqlClient;provider connection string=&quot;data source=(LocalDB)\v11.0;attachdbfilename=|DataDirectory| \EmpDB.mdf;integrated security=True;multipleactiveresultsets=True;application name=EntityFramework&quot;" providerName="System.Data.EntityClient" />
  </connectionStrings>

Failed to decrypt using provider error

It is important to note that when encrypting your config files the encryption key is stored locally on the server which means if you need to move your encrypted config file to another server you will need to either decrypt the config file first before moving it to the new server or export the key prior to moving and install it on the new server. If you move an encrypted config file to a server without exporting the encryption key you will receive an error like “Failed to decrypt using provider…. “.

So it is better to do any encryption and decryption on server itself where your web.config exists. rather creating RSA keys and moving them here and there. Last choice will be yours 🙂

For more information: https://msdn.microsoft.com/en-us/library/2w117ede.aspx

I Hope this will help !!!

Advertisements

ASP.NET 5 and AngularJS

Stephen Walther has written multiple part blog series on building ASP.NET 5 (ASP.NET vNext) apps with AngularJS. In this series of blog posts, he shown how you can create a simple Movie app using ASP.NET 5, MVC 6, and AngularJS. Go ahead and read these interesting and informative articles which will add to your learning of ASP.NET 5 with AngularJS.

Following are the topic and link of each blog posts:  

You can download the code discussed in this blog post from GitHub:

https://github.com/StephenWalther/MovieAngularJSApp

Hope this will help !!!

Configuring IIS 7 compression

Using compression is the single most effective way to reduce page load times. The .aspx files sent by the server to the browser consist of HTML. HTML is highly compressible by algorithms such as gzip. Because of this, modern web servers including IIS 5 and later have the ability to compress outgoing files, and modern browsers have the ability to decompress incoming files.

Both IIS 6 and IIS 7 offer advanced compression related options that help you get better performance improvements for your web site and make better use of your servers and bandwidth. Unfortunately, these options are not always easy to access. This article series shows step by step how to unlock these options.

In the first article in this two part series, we’ll focus on configuring IIS 7 compression. If you are used to IIS 6, you’ll find that IIS 7 offers many new features, including the ability to cache not only compressed static files, but also compressed dynamic files. If you still use IIS 6, the next article in the series will show how to configure IIS 6 compression.

This article is based on chapter 10 Compression of my book ASP.NET Site Performance Secrets.

Read Full Article : Configuring IIS 7 compression By Matt Perdeck

Hope this will help !!!!!

Action filters, service filters and type filters in ASP.NET 5 and MVC 6

Today, let’s have a look at he area of filters in ASP.NET MVC 6 – because it actually contains quite a few interesting changes compared to classic MVC and Web API filter pipelines.

Let’s leave the specialized filters (error filters, authorization filters) on a side for now, and focus instead on the functional, aspect oriented, filters. Aside from the good old action filters, known from both MVC and from Web API, there are two new types of filters (or rather filter factories, but we’ll get there) that you can use – ServiceFilters and TypeFilters.

Read Full Article : http://www.strathweb.com/2015/06/action-filters-service-filters-type-filters-asp-net-5-mvc-6/

Hope this will help !!!!!

Execute Long Running SQL Statements Asynchronously from .NET

Introduction

This tip aims at understanding the fundamental concept of asynchronous execution, i.e., how to use worker thread in colloboration with ADO.NET’s BeginExecute & EndExecute feature to avoid UI freeze.

Background

Below are the 2 main issues that arise when your application is intended to deal with huge data:

  1. SQL Server takes significant time to process (long running SQL statements) which leads to blocking the execution of your .NET code.

  2. Main thread or UI thread also gets blocked till the response from the SQL Server.

These issues are the serious issues while building interactive applications. User patience is an unpredictable parameter and user’s reaction against long waiting screen is uncertain. At-least UI shouldn’t freeze to engage the user and make him wait for the result.

Since, transactional SQL statements will definitely take time to process the things, the quickest solution sought is on the application programming level. Also, it is known that MS SQL server takes each & every call as synchronous, even if you change the connection string property AsynchronousProcessing to true. It is client application (C#, .NET) which gets affected. So, below are some widely used solutions.

Cancellation Token mechanism – so that user can cancel ongoing longer execution if they are unwilling to wait.

Callback mechanism – so that UI thread can’t get blocked

Read Full Article – Click

Hope this will help.

Jay Ganesh !!!!!