?
Solved

How do I encrypt the connection string in app.config

Posted on 2009-04-21
21
Medium Priority
?
3,694 Views
Last Modified: 2013-12-17
I need to encrypt the connection string in my windows application.  First, how do you encrypt the values in the app.config.  Second, how do I get the encrypted values out?

I am using C# .Net 3.5 so please give example in that format.

I am including a sample of what is in my app,config file.

I have a base provider class that I use in my data layer project to retrieve the connection string.  I am also including a sample of that code.

Please help me take my existing code and "fix" it to use an encrypted connection string.

Thanks in advance!
<connectionStrings>
    <add name="MyConnectionString" connectionString="Data Source=MyDataSource;Initial Catalog=MyCatalog;User ID=MyUserID;Password=MyPassword;" providerName="System.Data.SqlClient"/>
    </connectionStrings>
 
This is my base provider class.  It gets the connection string out of app.config (name variable below is the value "MyConnectionString" in app.config.  I 
-----------------------------------------------------
using System;
using System.Collections.Generic;
using System.Text;
using Microsoft.Practices.EnterpriseLibrary.Data;
 
namespace WP.Common.Data
{
    public abstract class BaseProvider
    {
        private Database _commonDatabase;
 
        protected Database CommonDatabase
        {
            get
            {
                if (DbManager.Instance != null)
                {
                    DbManager.Instance.CheckDatabase(_commonDatabase);
                }
                return _commonDatabase;
            }
            set
            {
                _commonDatabase = value;
            }
        }
 
        internal Database InternalDatabase
        {
            get
            {
                return _commonDatabase;
            }
        }
 
        protected BaseProvider(string name)
        {
            _commonDatabase = DatabaseFactory.CreateDatabase(name);
        }
 
    }
}
 
------------------------------------------
I then have a class that inherits the Base Provider like this
 
using System;
using System.Collections.Generic;
using System.Text;
 
namespace WP.Common.Data
{
    public class MySampleProvider: BaseProvider
    {
        public MySampleProvider()
            : base("MyConnectionString")  //this comes from app.config file
        {
        }
 
    }
}
 
 
 
Then in my data layer, I have my class inherit like this, and use the connection string to connect to my database...
 
    public class DatabaseProvider : MySampleProvider
    {
//methods here to do database stuff
//CommonDatabase is what is in my BaseProvider class.
DbCommand dbCommand = CommonDatabase.GetStoredProcCommand("Account_All");
 
}

Open in new window

0
Comment
Question by:bcesafsky
  • 6
  • 4
  • 4
  • +1
18 Comments
 
LVL 16

Expert Comment

by:CuteBug
ID: 24200493
See the code below


The following cose sample shows how to encrypt a string using c#
private string encryptString(string strToEncrypt)
{
System.Text.UTF8Encoding ue = new System.Text.UTF8Encoding();
byte[] bytes = ue.GetBytes(strToEncrypt);
 
// encrypt bytes
System.Security.Cryptography.MD5CryptoServiceProvi der md5 = new System.Security.Cryptography.MD5CryptoServiceProvi der();
byte[] hashBytes = md5.ComputeHash(bytes);
 
// Convert the encrypted bytes back to a string (base 16)
string hashString = "";
 
for(int i=0;i
{
hashString += Convert.ToString(hashBytes[i],16).PadLeft(2,'0');
}
 
return hashString.PadLeft(32,'0');
} 

Open in new window

0
 
LVL 16

Expert Comment

by:CuteBug
ID: 24200510
Hi,
The loop statement was not complete in the code given earlier

here is the complete code

The following cose sample shows how to encrypt a string using c#
private string encryptString(string strToEncrypt)
{
System.Text.UTF8Encoding ue = new System.Text.UTF8Encoding();
byte[] bytes = ue.GetBytes(strToEncrypt);
 
// encrypt bytes
System.Security.Cryptography.MD5CryptoServiceProvi der md5 = new System.Security.Cryptography.MD5CryptoServiceProvi der();
byte[] hashBytes = md5.ComputeHash(bytes);
 
// Convert the encrypted bytes back to a string (base 16)
string hashString = "";
 
for(int i=0;i < hashbytes.Length; i++)
{
hashString += Convert.ToString(hashBytes[i],16).PadLeft(2,'0');
}
 
return hashString.PadLeft(32,'0');
} 

Open in new window

0
 
LVL 16

Expert Comment

by:CuteBug
ID: 24200511
0
Concerto's Cloud Advisory Services

Want to avoid the missteps to gaining all the benefits of the cloud? Learn more about the different assessment options from our Cloud Advisory team.

 

Author Comment

by:bcesafsky
ID: 24204659
I need to take a step back and ask this... so with this solution, is the connection string removed from the app.onfig file?  Does your suggested code (the last one where you say it is a better solution), encrypt the entire file?

I'm still confused as to what to do.  I'm not sure if I remove the connection string from app.config and put it in a class that encrypts/decrypts??

Thanks again!  :-)
0
 
LVL 16

Expert Comment

by:CuteBug
ID: 24205247
what you should do is get the connection string, encrypt it and then put it in the app.config file.
When you are reading the app.config, get the encrypted string from app.config and decrypt it at runtime and then use the connection string...

You may create a class which deals with the encryption/decryption process.
0
 
LVL 41

Accepted Solution

by:
graye earned 750 total points
ID: 24208812
This becomes a sticky problem when you dive a little deeper...  for example, encrypting the connection string in the app.config works just fine when you "publish" your application, but it wreaks havoc when working in the Designer.   I solved this problem by creating a little external utility that only encrypted the connection string when the application is built, but leaves it as clear-text during design time.
The whole this a bit convoluted, so I'd reocmmend that you take a look at the following article (it's in VB.Net, but hey... that's probably close enough):  http://www.emmet-gray.com/Articles/EncryptConnectionStrings.htm
0
 

Author Comment

by:bcesafsky
ID: 24215260
Thanks, I am getting closer, I am trying to follow the instructions from this link, http://www.emmet-gray.com/Articles/EncryptConnectionStrings.htm
 but I believe the code is written in VS 2003 and I am using 2008.  I cannot open the sln or vbproj files because of we are on different versions of visual studio.  I know this is a lot to ask, but is anyone able to look at the link and convert it to VS2008?  I do not have the ability to install 2003 or 2005 or I would do it.  Also if you look at Part 3 from this link, I do not know where this is in VS 2008, can someone help with that?

Thanks!

This is the error I get when trying to open the sample from the link above
"make sure the application for the project type .vbproj is installed"
http://www.emmet-gray.com/Articles/EncryptConnectionStrings.htm
 
Part 3 - Putting the Pieces Together
You've probably used the My Project/Settings "tab" quite a few times, but never really looked at the properties box.   Each of the Settings has a Provider property (which is normally blank).   For each property that you want to obscure, you should change this property to use the name of the provider you created above.  You should also change the GenerateDefaultValueInCode property to False.

Open in new window

0
 
LVL 41

Expert Comment

by:graye
ID: 24215777
It was written with VS2005, which means that it should open in VS2008 with a prompt to convert the project.
Are you running the C# Express Edition?   If so, the sample in that link is VB.Net... so that means you'll need Visual Basic to be able to compile it.
0
 

Author Comment

by:bcesafsky
ID: 24215879
nope, I have the Professional edition SP1.  I normally write everything in C#, but I just tried to create a VB project and that works just fine.  I also have converted 2005 to 2008 recently and that worked fine too.

hmmmmmmm...
0
 
LVL 41

Expert Comment

by:graye
ID: 24216054
OK so you've got it compiled. but are having trouble finding the "Custom Settings Provides property in your C# project?  Yeah, me too...
http://www.google.com/search?hl=en&rls=com.microsoft%3Aen-us&q=custom+settings+provider+c%23&btnG=Search 
0
 

Author Comment

by:bcesafsky
ID: 24217926
nope, I still don't have it compiled, the projects won't open.
0
 
LVL 41

Expert Comment

by:graye
ID: 24220329
Just to confirm, I downloaded the zip file, extracted it to a temporary directory and double-clicked on the SLN (solution) file.   My VS2008 opened and asked me if I wanted to convert the project..
.... and that's not happening with you?
0
 

Author Comment

by:bcesafsky
ID: 24517291
I would like to leave this question open... unfortunately I had to move on to another project before I could spend quality time on this issue.  I tried following the suggestions and was not successful implementing them, so I would like to continue to hopefully get more responses, or to at least have more time to try the what has been suggested in more detail.  
0
 
LVL 1

Expert Comment

by:PainterEnterprises
ID: 24517457
You don't need encryption!  All you need is to make sure the end-user of your software can't just open up some plain-text config file and read or modify the connection string stored in it.

I'm personally a big fan of Obfuscation.

Just kick your plain text connection string out to a hexadecimal string that only a real geeky geek would be able to meddle with.  At this point, you can actually do a whole lot with it before you write it to the file; pad the beginning or end with a certain amount of random values to further conceal the 'valid' portion of the string, or before you go from String to Hex String you could also get the underlying byte values and do a little bitshifting and/or valueshifting so that the actual hex values stored only represent your connection string if the correct math (hard coded into your application) is run against it.

Consider the provided example, and best of luck to you.

        Dim MyConnectionString As System.String = "Database=Some Database;schema=someschema;username=someusername;password=somepassword"
 
        Dim MyObfuscatedString As System.String = ""
        For Each charac As Char In MyConnectionString
            MyObfuscatedString &= Hex(Asc(charac))
        Next
        MsgBox(MyObfuscatedString)
 
        Dim MyDeObfuscatedString As System.String = ""
        For deob_idx As System.Int32 = 0 To (MyObfuscatedString.Length - 1)
            Dim HexVal As System.String = MyObfuscatedString(deob_idx) & MyObfuscatedString((deob_idx + 1))
            Dim ByteVal As System.Byte = "&H" & HexVal
            MyDeObfuscatedString &= Chr(ByteVal)
 
            deob_idx += 1
        Next deob_idx
        MsgBox(MyDeObfuscatedString)

Open in new window

0
 
LVL 1

Expert Comment

by:PainterEnterprises
ID: 24517473
AHEM!

My bad.

# {
#     System.String MyConnectionString = "Database=Some Database;schema=someschema;username=someusername;password=somepassword";
#    
#     System.String MyObfuscatedString = "";
#     foreach (char charac in MyConnectionString) {
#         MyObfuscatedString += Conversion.Hex(Strings.Asc(charac));
#     }
#     Interaction.MsgBox(MyObfuscatedString);
#    
#     System.String MyDeObfuscatedString = "";
#     for (System.Int32 deob_idx = 0; deob_idx <= (MyObfuscatedString.Length - 1); deob_idx++) {
#         System.String HexVal = MyObfuscatedString(deob_idx) + MyObfuscatedString((deob_idx + 1));
#         System.Byte ByteVal = "&H" + HexVal;
#         MyDeObfuscatedString += Strings.Chr(ByteVal);
#        
#         deob_idx += 1;
#     }
#     Interaction.MsgBox(MyDeObfuscatedString);
# }

Open in new window

0
 
LVL 1

Expert Comment

by:PainterEnterprises
ID: 24517502
Actually, nevermind.  I used a free, fast VB to C# converter and posted before I tested.  That C# code above is garbage.  Utter garbage.

The VB code works great, though, at least for demonstration or 'proof of concept' purposes.  Hopefully you'll be able to see what it is I'm suggesting.
0
 
LVL 1

Expert Comment

by:PainterEnterprises
ID: 24518812
Hi, modus_operandi.

I believe 24200510 and also 24208812 are perfectly valid solutions to the original issue described, but that the original author had difficulty implementing the first and then difficulty loading some files downloaded in pursuit of the second into his version of Visual Studio.  It looks like both solution providers attempted to provide technical support to help the original author get it working for him, but as he said himself he got distracted by other projects.

I recommend option #3, post ID 24200510 and post ID 242008812 as solutions.

I might also note that even though I posted in the wrong forum (not sure why EE emailed me about a C# posting in the first place, and I didn't discover it was a C# Forum until I'd already posted), my post ID 24517457 is a fully functional code snippet demonstrating light string value obfuscation and de-obfuscation in VB.
0
 

Author Closing Comment

by:bcesafsky
ID: 31573058
Thank you for your time, it was greatly appreciated!
0

Featured Post

How to Use the Help Bell

Need to boost the visibility of your question for solutions? Use the Experts Exchange Help Bell to confirm priority levels and contact subject-matter experts for question attention.  Check out this how-to article for more information.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

In real business world data are crucial and sometimes data are shared among different information systems. Hence, an agreeable file transfer protocol need to be established.
Hello there! As a developer I have modified and refactored the unit tests which was written by fellow developers in the past. On the course, I have gone through various misconceptions and technical challenges when it comes to implementation. I would…
The Email Laundry PDF encryption service allows companies to send confidential encrypted  emails to anybody. The PDF document can also contain attachments that are embedded in the encrypted PDF. The password is randomly generated by The Email Laundr…
With Secure Portal Encryption, the recipient is sent a link to their email address directing them to the email laundry delivery page. From there, the recipient will be required to enter a user name and password to enter the page. Once the recipient …
Suggested Courses
Course of the Month14 days, 7 hours left to enroll

839 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question