Which way is the best to encrypt the connstring in the app.config?
- use
cryptographyto encrypt and decrypt, or - use
%windir%\Microsoft.NET\Framework\v2.0.50727\aspnet_regiis -pef "connectionStrings" "C:\documents and settings\bob\projects\myproject", like recommended in Protect App.Config file or Encrypt.
Concerns:
1) If i use Crytography, everything works fine. Except that this code below will always be called each time when you run into using (leDataContext db = new leDataContext()), which causes me to feel that it will slow down the system.
public partial class leDataContext
{
public leDataContext()
: base("")
// : base(ConfigurationManager.ConnectionStrings["leConnString"].ToString())
{
string decrypted = Cryptography.Decrypt(ConfigurationManager.ConnectionStrings["leConnString"].ToString());
base.Connection.ConnectionString = decrypted;
}
}
2) If I use the method 2, it sounds good as it will automatically do the encryption. However, should I keep those encrypted <CipherValue>rUmEA8h02uMZ5M4uEVtL+5M/UvPuyJ4UJz5d/P...</CipherValue> in my app.conf when I do publish using ClickOnce?
It is because those the method 2 can only be done at the client machine. So should I perform method 2 at client machine, then copy those encrypted code to a file, and each time when I want publish using clickOnce, then copy it manually back to the App.config before publishing, so that the client will update the right connstring?
Cryptography code:
internal static string Encrypt(string sender, string key)
{
string text1;
if (sender == null) sender = "";
byte[] buffer4 = new byte[0];
byte[] buffer1 = buffer4;
byte[] buffer2 = new byte[] { 110, 120, 130, 140, 150, 160, 170, 180 };
try
{
buffer1 = Encoding.UTF8.GetBytes(key.Substring(0, 8));
DESCryptoServiceProvider provider1 = new DESCryptoServiceProvider();
byte[] buffer3 = Encoding.UTF8.GetBytes(sender);
MemoryStream stream1 = new MemoryStream();
CryptoStream stream2 = new CryptoStream(stream1, provider1.CreateEncryptor(buffer1, buffer2), CryptoStreamMode.Write);
stream2.Write(buffer3, 0, buffer3.Length);
stream2.FlushFinalBlock();
text1 = Convert.ToBase64String(stream1.ToArray());
}
catch (Exception ex)
{
text1 = string.Empty;
}
return text1;
}
Could you advice?