0

I used connection string in app.config file in c#. I want to change connection string dynamically. I used a form to change the connection string. i want when i change server configuration and click to save it the connection string encrypted. i use a text box to encrypted password field when text changed.i use following code to encrypted connection string. it save the connection string encrypted but my software not connect the database for the encryption. It shows no valid password. How to Solve this problem? enter image description here

private void btnSave_Click(object sender, EventArgs e)
        {
            DBPath = cbodbsource.Text + txtdbname.Text;
            //Set connection string
            string connectionString = string.Format("Provider={0};Data Source={1};Jet OLEDB:Database Password={2};", cboProvider.Text, DBPath, txtdbpassword.Text);
            try
            {
                OledbHelper helper = new OledbHelper(connectionString);
                if (helper.IsConnection)
                {
                    AppSetting setting = new AppSetting();
                    setting.SaveConnectionString("con", connectionString);
                    MessageBox.Show("Your connection string has been successfully saved.", "Message", MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "Message", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

string Encrypt(string source, string key)
        {
            using (TripleDESCryptoServiceProvider tripleDESCryptoService = new TripleDESCryptoServiceProvider())
            {
                using (MD5CryptoServiceProvider hashMD5Provider = new MD5CryptoServiceProvider())
                {
                    byte[] byteHash = hashMD5Provider.ComputeHash(Encoding.UTF8.GetBytes(key));
                    tripleDESCryptoService.Key = byteHash;
                    tripleDESCryptoService.Mode = CipherMode.ECB;
                    byte[] data = Encoding.UTF8.GetBytes(source);
                    return Convert.ToBase64String(tripleDESCryptoService.CreateEncryptor().TransformFinalBlock(data, 0, data.Length));
                }
            }
        }

I have used text_Changed Event Code. Here is it

private void txtdbpassword_TextChanged(object sender, EventArgs e)
{
    txtEncrypt.Text = this.Encrypt(txtdbpassword.Text, "myconstring");
}
  • Where do you call the Encrypt function? – Tarik Jan 15 '20 at 19:26
  • I want to save connection string dynamically like this: – Mithila Das Jan 16 '20 at 05:30
  • I dont get it... You encrypt the password on text changed? and then try to use it to open a connection? To open the connection you need the clear unencrypted text for all connection string fields including the password. – Jonathan Alfaro Jan 16 '20 at 05:35
  • Dear @Darkonekt Above encrypted connection string is working. How it working without decrypt clear text? – Mithila Das Jan 16 '20 at 05:40
  • you have connection string encrypted in the config, ok. But what error do you have when trying to connect the db? You are using the custom encryption module so you have to decrypt the connection string manually when reading it from the config file. Another option is to use [SectionInformation.ProtectSection method](https://learn.microsoft.com/en-us/dotnet/api/system.configuration.sectioninformation.protectsection?view=netframework-4.8) – oleksa Jan 16 '20 at 09:32
  • How to decrypt connection string? Please give me sample code or project. – Mithila Das Jan 16 '20 at 14:58

2 Answers2

0

Although you are using known cryptographic functions, you should rely on built in mechanisms that encrypt your connection string through configuration instead of coding it yourself. The reason being that you will have to store the decryption key somewhere safe.

For example IIS provides support for this. Read here: https://techcommunity.microsoft.com/t5/iis-support-blog/connection-string-encryption-and-decryption/ba-p/830094

Moreover, if you encrypt anything with an embedded key within your exe, minutes will be sufficient to decompile your application and extract the key. As such, you should use Windows Integrated Authentication instead of SQL Server Authentication.

Tarik
  • 10,810
  • 2
  • 26
  • 40
  • He's not rolling his own encryption. In his code he is clearly using TripleDES with MD5. Actually read questions before answering them. You don't have to recompile to pick up a change in config. –  Jan 16 '20 at 17:46
  • @Josh I do not claim he does his own encryption although the wording might have lead to that conclusion. The rest of the answer clarify things up. Fixed my answer to clarify my point of view. – Tarik Jan 16 '20 at 18:36
-1

I use a class to encrypt my connection string and i successfully encrypted my connection string. But i could not decrypted the encrypted when connect db. My class name is EncryptPass and code is

public static string EncryptPassword(string password)
        {
             //Using MD5 to encrypt a string
            using (MD5CryptoServiceProvider md5 = new MD5CryptoServiceProvider())
            {
                UTF8Encoding utf8 = new UTF8Encoding();
                //Hash data
                byte[] data = md5.ComputeHash(utf8.GetBytes(password));
                return Convert.ToBase64String(data);
            }
        }
    }
My encrypted connection string code is:

<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <connectionStrings>
    <add name="con"
       connectionString="JEXBqoI4UL2QA3IClyVMOA=="
       providerName="System.Data.OleDb" />
  </connectionStrings>
  <startup useLegacyV2RuntimeActivationPolicy="True">
    <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.0"/>
  </startup>
</configuration>

I Use this following code to decrypt but not work.

con = new OleDbConnection(EncryptPass.EncryptPassword(ConfigurationManager.ConnectionStrings["con"].ConnectionString));

Its shows an error enter image description here

  • well, decryption is opposite to encryption. You can't use the same `EncryptPass.EncryptPassword` to encrypt and decrypt data . Please check [the sample how to decrypt and encrypt data](https://stackoverflow.com/questions/11413576/how-to-implement-triple-des-in-c-sharp-complete-example). – oleksa Jan 17 '20 at 09:29