Click here to Skip to main content
14,453,298 members
Rate this:
Please Sign up or sign in to vote.
See more:
i encrypt my app connectionstring but when i launch the app that decrypt the connection string and connect to my database the connection string maintain in the encrypted format

What I have tried:

i'm training to decrypt my encrypted connection string putted in app.config , so in first i crypt it thani replaced the real one by the crypted chaine and it look
<?xml version="1.0" encoding="utf-8"?>
<configuration>
    <configSections>
    </configSections>
    <connectionStrings>
        <add name="Benificiare.Properties.Settings.LogementConnectionString" connectionString="6uDB/32KxMOEPPO0maQDJ63Adjp7okmRdGd9s67mV5+8v6wiRK8UKWscnJSbQzFZTQCLiHQnZPGC8S6lI5Uw28qgjKLL14bkL8sNaDkwRUZ+bB6GMFelH9OVZpG1p+4T/I1LosmrkHylQKHotPFZg3xq3EwDJOY3rjbgE5mu6ow=" providerName="System.Data.SqlClient"/>
    </connectionStrings>
<startup><supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.6.1"/></startup></configuration>


in my code i do the inverse


Configuration configuration = null;
            string connection = null;
           configuration = ConfigurationManager.OpenExeConfiguration(@".\Myapp.exe");
            connection = ConfigurationManager.ConnectionStrings["Benificiare.Properties.Settings.LogementConnectionString"].ConnectionString;
            string ENC = DecryptString(connection, "KEY");    //decrypte the connection string                   
            configuration.ConnectionStrings.ConnectionStrings["Benificiare.Properties.Settings.LogementConnectionString"].ConnectionString = ENC;


when i try to connect i'll have message indecate that the connectionstring is not changed.
Posted
Updated 22-May-19 3:36am
v2
Rate this:
Please Sign up or sign in to vote.

Solution 1

This line:
connection = ConfigurationManager.ConnectionStrings["Myapp.Properties.Settings.LogementConnectionString"].ConnectionString;
seeks for a connection named Myapp.Properties.Settings.LogementConnectionString.

But this line:
<add name="Benificiare.Properties.Settings.LogementConnectionString" ...
declares the connection under the name Benificiare.Properties.Settings.LogementConnectionString.

Either you misnamed the connection in the XML file, or you misnamed it when you try to fetch it from your C# code. I'm surprised this code does not produce an exception at runtime when you try to access an unexistent connection string.

Your best option here is to start using your debugger^. Debugging is a very funny part of a developer's job, I warmly encourage you to give it a try as you even may find it entertaining.

Put a breakpoint^ on the line you wish to start debugging from, and launch the debug session (see above link for that).

We cannot do that for you, nor do we have all relevant informations. Learning to do it yourself could bring you quite a satisfaction, though.
   
Comments
Amar zaidi 20-May-19 5:46am
   
i don't mis any think, the connection is declared correctly, i change only the word benificiare by my MyApp when i was writing the qustion the
real pb is How to change
ConfigurationManager.OpenExeConfiguration(@".\Benificiare.exe").ConnectionStrings.CurrentConfiguration.ConnectionStrings.ConnectionStrings["Benificiare.Properties.Settings.LogementConnectionString"].ConnectionString = ENC;

when i debbug the string ENC become null and it maintaine the encrypted chaine
phil.o 20-May-19 5:52am
   
Then, this is the DecryptString() method that you have to debug further, since it returns a null value. You did not show its implementation in your code sample. But no big deal: just as you have debugged the portion of the code that you showed, now debug the DecryptString() method, and get why it returns a null value from the encoded string obtained from configuration.
Edit: I corrected your code block so other members are not mislead by a typo.
Amar zaidi 21-May-19 4:43am
   
i fix it
Rate this:
Please Sign up or sign in to vote.

Solution 2

i debug it and it works correctly,
my idea is divided in two steps
1- i encrypt the connectionstring so i take it from app.config and i encrypt it outsid with an Encrypt() function then string returned i replace it with the app.config connectionstring .
2- in my app and when it loading i have to extract the connectionstring from the app.config
connection =
ConfigurationManager.OpenExeConfiguration(@".\Benificiare.exe").ConnectionStrings.ConnectionStrings["Benificiare.Properties.Settings.LogementConnectionString"].ConnectionString;

then i decrypt it

string ENC = DecryptString(connection, "MyPassPhrase");


then ihave to change my connectionstring

ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None).ConnectionStrings.CurrentConfiguration.ConnectionStrings.ConnectionStrings["Benificiare.Properties.Settings.LogementConnectionString"].ConnectionString = ENC;


my fault was the pb of the run time (file was protected ), so i fix it using OpenExeConfiguration(ConfigurationUserLevel.None) Instead
OpenExeConfiguration(@".\Myapp.exe")
   
Rate this:
Please Sign up or sign in to vote.

Solution 3

I think you may be over complicating things a bit. Given an app.config file like this

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <connectionStrings>
    <clear />
    <add name="MyConnection"
     providerName="System.Data.ProviderName"
     connectionString="Tie two pieces of string together" />
  </connectionStrings>
    <startup> 
        <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.6.1" />
    </startup>
</configuration>


The following app shows a way of managing encryption and decryption. It's based largely on this documentation.

using System;
//may need to add reference to System.Configuration
using System.Configuration;
namespace Scratch
{
    class Program
    {
        static void Main(string[] args)
        {
                                        //path to the exe file
            EnsureConnectionIsEncrypted(@".\Scratch.exe");
            //To do:use a text reader to check .\Scratch.exe.config 
            //now has an encrypted connection
            //Note: The App.config file in solution explorer is not changed
            //To retrieve the decrypted string, simply do this:- 
            var connectionString = ConfigurationManager.ConnectionStrings["MyConnection"].ConnectionString;
            Console.WriteLine(connectionString);
            Console.ReadLine();
        }
        //The encryption must be enacted on the client machine, 
        //as decryption can only be done by the machine 
        //that performed the encryption
        static void EnsureConnectionIsEncrypted(string exeFileName)
        {
                 Configuration config = ConfigurationManager.
                    OpenExeConfiguration(exeFileName);
                ConnectionStringsSection section =
                    config.GetSection("connectionStrings")
                    as ConnectionStringsSection;
                if (!section.SectionInformation.IsProtected)
                {
                    section.SectionInformation.ProtectSection(
                       "DataProtectionConfigurationProvider");
                    config.Save();
                }
        }
    }
}


After encryption, the exe.config file in the output directory will look something like this, the actual CipherValue has been truncated.

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <connectionStrings configProtectionProvider="DataProtectionConfigurationProvider">
    <EncryptedData>
      <CipherData>
        <CipherValue>AQAAANCMnd8BFdERjHoAwE/Cl........................</CipherValue>
      </CipherData>
    </EncryptedData>
  </connectionStrings>
    <startup> 
        <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.6.1" />
    </startup>
</configuration>

   
Comments
Amar zaidi 22-May-19 8:12am
   
it works but if i try to deploy my app in other machine it doesn't work
George Swan 22-May-19 10:28am
   
The exe.config file on the client machine must be unencrypted when the app first runs. Only the machine that encrypts the connection string can decrypt it.
Amar zaidi 23-May-19 6:29am
   
and how that can be happen.
because i thing that your solution is better then mine, i looked at some video talk about exporting and importing keys useing aspnet_regiis but till now i m not applicate it correctly
Rate this:
Please Sign up or sign in to vote.

Solution 4

finly i have the solution and it work
so as i said befor i encrypt my connectionstring elsewhere with an Encrypt() function then i but the crypted chaine ine the Place of my connectionstring in APP.CONFIG

<pre><?xml version="1.0" encoding="utf-8"?>
<configuration>
    <configSections>
    </configSections>
    <connectionStrings>
        <add name="Benificiare.Properties.Settings.LogementConnectionString" connectionString="6uDB/32KxMOEPPO0maQDJ63Adjp7okmRdGd9s67mV5+8v6wiRK8UKWscnJSbQzFZTQCLiHQnZPGC8S6lI5Uw28qgjKLL14bkL8sNaDkwRUZ+bB6GMFelH9OVZpG1p+4T/I1LosmrkHylQKHotPFZg3xq3EwDJOY3rjbgE5mu6ow=" providerName="System.Data.SqlClient"/>
    </connectionStrings>
<startup><supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.6.1"/></startup></configuration>


THE NAME OF CONNECTION IS
Benificiare.Properties.Settings.LogementConnectionString

and the encrypted chaine is
"Benificiare.Properties.Settings.LogementConnectionString" connectionString="6uDB/32KxMOEPPO0maQDJ63Adjp7okmRdGd9s67mV5+8v6wiRK8UKWscnJSbQzFZTQCLiHQnZPGC8S6lI5Uw28qgjKLL14bkL8sNaDkwRUZ+bB6GMFelH9OVZpG1p+4T/I1LosmrkHylQKHotPFZg3xq3EwDJOY3rjbgE5mu6ow="

when the app is running i have to decrypt this chaine and use the decrypted as a connectionstringg of my app so what i do is
Configuration  configuration = ConfigurationManager.OpenExeConfiguration(@".\Myapp.exe");
            connection = ConfigurationManager.ConnectionStrings["Benificiare.Properties.Settings.LogementConnectionString"].ConnectionString;
            string ENC = DecryptString(connection, "KEY");    //decrypte the connection string                   
            configuration.ConnectionStrings.ConnectionStrings["Benificiare.Properties.Settings.LogementConnectionString"].ConnectionString = ENC; // change the connectionstring of the app with the decrypted one ****** but this variable was in mode readonly so my pb was in this instruction



so what i have to do, is to change the last instruction with

var settings = ConfigurationManager.ConnectionStrings["Benificiare.Properties.Settings.LogementConnectionString"];
           var field = typeof(ConfigurationElement).GetField( "_bReadOnly", System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic);
           field.SetValue(settings, false);
           settings.ConnectionString = ENC;



and it works pefectly
   

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)




CodeProject, 503-250 Ferrand Drive Toronto Ontario, M3C 3G8 Canada +1 416-849-8900 x 100