Encrypt And Decrypt Connection String In Web.Config File (2024)

As you all know the connection string is the pillar of our data. I mean, without a connection string you just can’t create an application which does some database actions like retrieving the data, creating the data, etc. We all know that the connection string is placed in the file called web config. If anyone needs to get the database information of your application, the first place he/she may look at will be the web config file. Am I right? It is always recommended to encrypt the connection string of your application because the data we have there is highly sensitive. It must be secured. Here I am going to show you a demo of how we can do that. You can do the same thing in your Web API project, MVC project, Asp.Net 5 project, or any kind of templates you works with. I hope you will like this.

Background

I used to secure my config file if I am the who starts the project. Here you will get to know how easy the procedure is to encrypt the connection string. There is only a few steps to be followed. I will explain those.

Agenda

The following is the agenda we are going to follow.

  • Create an empty project, it can be any template (ASP.NET 5, Web API, MVC…)
  • Add a connection string
  • Encrypt the connection string
  • Decrypt the connection string

Perquisites

  • Visual Studio
  • SQL Server

Create an empty project

To create an empty project, go to File->New->New Project->Name the project->Select Empty->Click OK. Hope you get a solution as follows.

Encrypt And Decrypt Connection String In Web.Config File (1)

Figure: Empty Solution

Now We will connect to a database. To connect, please click on the connect icon in your server explorer window and connect you Local/Server database.

Encrypt And Decrypt Connection String In Web.Config File (2)

Figure: Connect to Database

Add a connection string

Now it is time to add our connection string, hope you got your data source of the database we already connected. The connection string property must be placed under configuration tag in your web config file. Here is mine.

  1. <connectionStrings>
  2. <addname="myConnection"connectionString="DataSource=SIBEESHVENU\SQLEXPRESS;InitialCatalog=ReportServer$SQLEXPRESS;IntegratedSecurity=True"/>
  3. </connectionStrings>

Now we will create a web page and in the page load event we will fetch this connection string and write it as a response.

  1. usingSystem;
  2. usingSystem.Collections.Generic;
  3. usingSystem.Linq;
  4. usingSystem.Web;
  5. usingSystem.Web.UI;
  6. usingSystem.Web.UI.WebControls;
  7. namespaceEncryptConnectionString
  8. {
  9. publicpartialclassDefault:System.Web.UI.Page
  10. {
  11. protectedvoidPage_Load(objectsender,EventArgse)
  12. {
  13. if(!IsPostBack)
  14. {
  15. try
  16. {
  17. stringmyCon=System.Configuration.ConfigurationManager.ConnectionStrings["myConnection"].ConnectionString;
  18. if(myCon!=null)
  19. {
  20. Response.Write("Myconnectionstringis:"+myCon);
  21. }
  22. }
  23. catch(Exception)
  24. {
  25. throw;
  26. }
  27. }
  28. }
  29. }
  30. }

Please run your page, you will see your connection string in your page.

Encrypt connection string

To start the process, you must open your command window with the admin privilege. Then type the following command.

  1. cdC:\Windows\Microsoft.NET\Framework\v4.0.30319

This command will narrate you to the framework version folder given. Now right click on your project and click open folder in file explorer and then copy the location. For me it is F:\Visual Studio\EncryptConnectionString\EncryptConnectionString. Now please go back to your command prompt and type the command as follows.

  1. ASPNET_REGIIS-PEF"connectionStrings""F:\VisualStudio\EncryptConnectionString\EncryptConnectionString"

Once you click the enter. You will get the output as follows.

Encrypt And Decrypt Connection String In Web.Config File (4)

Figure: Encrypt ConnectionString Output

Please be noted that the text connectionStrings is case sensitive. If you don’t give it as it is, you will get an error as follows.

  1. C:\Windows\Microsoft.NET\Framework\v4.0.30319>ASPNET_REGIIS-PEF"connectionstrings""F:\VisualStudio\EncryptConnectionString\EncryptConnectionString"
  2. Microsoft(R)ASP.NETRegIISversion4.0.30319.0
  3. AdministrationutilitytoinstallanduninstallASP.NETonthelocalmachine.
  4. Copyright(C)MicrosoftCorporation.Allrightsreserved.
  5. Encryptingconfigurationsection...
  6. Theconfigurationsection'connectionstrings'wasnotfound.
  7. Failed!

So please be careful while you type the commands. Now I am going back to our application and see the config file. Shall we? You can see the connection string is encrypted as follows.

  1. <connectionStringsconfigProtectionProvider="RsaProtectedConfigurationProvider">
  2. <EncryptedDataType="http://www.w3.org/2001/04/xmlenc#Element"xmlns="http://www.w3.org/2001/04/xmlenc#">
  3. <EncryptionMethodAlgorithm="http://www.w3.org/2001/04/xmlenc#tripledes-cbc"/>
  4. <KeyInfoxmlns="http://www.w3.org/2000/09/xmldsig#">
  5. <EncryptedKeyxmlns="http://www.w3.org/2001/04/xmlenc#">
  6. <EncryptionMethodAlgorithm="http://www.w3.org/2001/04/xmlenc#rsa-1_5"/>
  7. <KeyInfoxmlns="http://www.w3.org/2000/09/xmldsig#">
  8. <KeyName>RsaKey</KeyName>
  9. </KeyInfo>
  10. <CipherData>
  11. <CipherValue>B4B3oZrbpQsYM7Eaq5smukqDj9XUYUCwygBYRG1iasN4ll5W4wAKVCIFCRfvOJGoIXzgqpyjAI30IKf5pnZ/xWqmo3p/wGfOKdMrzd041dt9llLGbxFpLJs0Nkm583PJ1FppXLAy7FOD0YoBVhG/PBtBgLjTQqcXRNbVcgufzuArlv/EH+7lzSNRclXSTMOPMtISF65hPI9ICj9qLx7RBGhVZ6uFZVFteyyuRd2i3D2r7wJfr6KflFkakdxp1OWE2JK4Ldb8kZSwAy3bNaI/qaV9EgIWt9wM6RZO/IrI3kI/bX8JuvirPw3j/+TLDB3MoIgKjSbLpR3GYTm9csPu8g==</CipherValue>
  12. </CipherData>
  13. </EncryptedKey>
  14. </KeyInfo>
  15. <CipherData>
  16. <CipherValue>0n1Y6ScSNZDR4x1sXfK05w9h+pp2OrAEQFQsoAUP5Y/hPsfpJS/7jv21PbPlkYmdCzycM4PGGb0+fuffR3RuL1x0tn7rfyUdA9llTfkyRQKwS9xOmkMsVFXgQDr8P4aXGef1fZPE2gjhcjm/JQToLwsfQZK1gNr4d6cIPFNqKD6wt24F7fuySJPX3OgLb8wXfQMd7ij+JcZzNlnyNHbq/DIjxSpPOnMrC52t06Jj8F8+MsSud9GcijcFB2UhvLVXQwyZ51nEj6Tf36Zbca8bgw==</CipherValue>
  17. </CipherData>
  18. </EncryptedData>
  19. </connectionStrings>

Decrypt connection string

You can always decrypt the connection string if you want, to decrypt you just need follows the commands as follows in the command prompt.

  1. cdC:\WINDOWS\Microsoft.NET\Framework\v4.0.30319

Once after you did you the above command you can execute the preceding one.

  1. ASPNET_REGIIS-PDF"connectionStrings""F:\VisualStudio\EncryptConnectionString\EncryptConnectionString"

The text ‘connectionString’ is case sensitive as mentioned above

If the command is correct, you can get an output as follows.

Encrypt And Decrypt Connection String In Web.Config File (5)

Figure: Decrypting connectionString

Now if you check your Web config again, you can see the connection string has got encrypted. Have a happy coding!.

Conclusion

Did I miss anything that you may think is needed? Did you find this post useful? I hope you liked this article. Please share with me your valuable suggestions and feedback.

Your turn. What do you think?

A blog isn’t a blog without comments, but do try to stay on topic. If you have a question unrelated to this post, you’re better off posting it on C# Corner, Code Project, Stack Overflow, Asp.Net Forum instead of commenting here. Tweet or email me a link to your question there and I’ll definitely try to help if I can.

Please see this article in my blog here

Encrypt And Decrypt Connection String In Web.Config File (2024)
Top Articles
Speculation vs. Gambling: What's the Difference?
Interpretation: The Taxing Clause | Constitution Center
Napa Autocare Locator
Www.politicser.com Pepperboy News
Phone Number For Walmart Automotive Department
Comforting Nectar Bee Swarm
Beds From Rent-A-Center
Crime Scene Photos West Memphis Three
Carter Joseph Hopf
Dark Souls 2 Soft Cap
Seth Juszkiewicz Obituary
Craigslist Cars Nwi
6th gen chevy camaro forumCamaro ZL1 Z28 SS LT Camaro forums, news, blog, reviews, wallpapers, pricing – Camaro5.com
The Shoppes At Zion Directory
Restaurants Near Paramount Theater Cedar Rapids
Swedestats
Ratchet & Clank Future: Tools of Destruction
Caledonia - a simple love song to Scotland
EASYfelt Plafondeiland
Winco Employee Handbook 2022
Ac-15 Gungeon
Www.dunkinbaskinrunsonyou.con
Chime Ssi Payment 2023
Turbo Tenant Renter Login
Cb2 South Coast Plaza
At 25 Years, Understanding The Longevity Of Craigslist
Panolian Batesville Ms Obituaries 2022
No Limit Telegram Channel
208000 Yen To Usd
Table To Formula Calculator
Weather Underground Durham
County Cricket Championship, day one - scores, radio commentary & live text
Grand Teton Pellet Stove Control Board
Craigslist Central Il
Amici Pizza Los Alamitos
Metro 72 Hour Extension 2022
Louisville Volleyball Team Leaks
Reborn Rich Ep 12 Eng Sub
Dr Adj Redist Cadv Prin Amex Charge
The Thing About ‘Dateline’
Silive Obituary
התחבר/י או הירשם/הירשמי כדי לראות.
Exam With A Social Studies Section Crossword
Rocket Lab hiring Integration &amp; Test Engineer I/II in Long Beach, CA | LinkedIn
Aznchikz
Used Auto Parts in Houston 77013 | LKQ Pick Your Part
15:30 Est
Rocket Bot Royale Unblocked Games 66
Coleman Funeral Home Olive Branch Ms Obituaries
Nfsd Web Portal
Buildapc Deals
Lorcin 380 10 Round Clip
Latest Posts
Article information

Author: Fr. Dewey Fisher

Last Updated:

Views: 5676

Rating: 4.1 / 5 (62 voted)

Reviews: 93% of readers found this page helpful

Author information

Name: Fr. Dewey Fisher

Birthday: 1993-03-26

Address: 917 Hyun Views, Rogahnmouth, KY 91013-8827

Phone: +5938540192553

Job: Administration Developer

Hobby: Embroidery, Horseback riding, Juggling, Urban exploration, Skiing, Cycling, Handball

Introduction: My name is Fr. Dewey Fisher, I am a powerful, open, faithful, combative, spotless, faithful, fair person who loves writing and wants to share my knowledge and understanding with you.