c# – Save the connection in app.config in an encrypted way

Question:

Is it possible to save a connection string from app.config without saving the password, or somehow encrypt it, using entity framework? Without using windows authentication, I mean with username and password.

Connection example:

<add name="conexionEntities" connectionString="metadata=res://*/Integration.Models.conexion.csdl|res://*/Integration.Models.conexion.ssdl|res://*/Integration.Models.conexion.msl;provider=System.Data.SqlClient;provider connection string=&quot;data source=(local);initial catalog=db_ejemplo;user id=sa;password=123456789;multipleactiveresultsets=True;App=EntityFramework&quot;" providerName="System.Data.EntityClient" />

password = 123456789 <- this data is what I would not like to be exposed in the app.config

Answer:

You can encrypt parts of the Web.config as shown in the link to prevent that information from being accessed.

EDIT

Example of the encryption process:

  1. Edit the Web.config with a text editor. Make sure <system.web> contains child elements: <connectionStrings> and <machineKey> . An example could be:
<configuration>
   <connectionStrings>
      <add name="SqlServices" connectionString="Data Source=localhost;Integrated Security=SSPI;Initial Catalog=Northwind;" />
   </connectionStrings>
   <system.web>
     <machineKey validationKey="D61B3C89CB33A2F1422FF158AFF7320E8DB8CB5CDA1742572A487D94018787EF42682B202B746511891C1BAF47F8D25C07F6C39A104696DB51F17C529AD3CABE"
       decryptionKey="FBF50941F22D6A3B229EA593F24C41203DA6837F1122EF17" />
   </system.web>
</configuration>
  1. With the command prompt go to: cd \WINDOWS\Microsoft.Net\Framework\v2.0.*

  2. Once there, run the following command: aspnet_regiis -pe "connectionStrings" -app "/MyApplication" . This command encrypts the <connectionStrings> of the MyApplication application.

  3. Repeat the previous step for the <machineKey> element: aspnet_regiis -pe "system.web/machineKey" -app "/MyApplication"

Now the content of the Web.config is already encrypted.

EXTRA

Access to encrypted data:

Although ASP.NET automatically decrypts the content of the Web.config file when it processes it and no additional steps are required to read the file, it can be interesting to know how to view the decrypted information. To access it, it can be done using these lines of code.

  Configuration config = WebConfigurationManager.OpenWebConfiguration(Request.ApplicationPath);
  MachineKeySection key = 
    (MachineKeySection)config.GetSection("system.web/machineKey");
Scroll to Top