How to encrypt a connection string using EF 4.1 Code First?

I am using Code First RC to create a class library, and I would like to be able to encrypt the connection string that I am using. Class library users can be ASP.NET or Windows Forms applications, so I need an encryption method that works with both.

It looks like I can pass the connection string to DbContext by name, but not by value, as shown here , so I don't think I can manually decrypt in my program before passing the string to DbContext. Can someone point me in the right direction?

+4
source share
2 answers

You can easily encrypt any section of the .NET configuration, not only in ASP.NET, as it seems to many developers, but absolutely also in other applications.

Check out Jon Galloway's blog post on the topic - well read!

Using this approach, you can encrypt the <connectionStrings> section - and to make it even easier, you can also screen this section into a separate file.

So, in your app.config for your Winforms application, you should:

 <connectionStrings configSource="ConnectionStrings.config" /> 

and the same will be in your web.config for your web application, and the referenced file will only contain <connectionStrings> and can be encrypted. Download the appropriate connection string from your configuration and pass it to your DbContext constructor, and everything will be fine.

+3
source

You can pass the full connection string to the DbContext:

http://blogs.msdn.com/b/adonet/archive/2011/01/27/using-dbcontext-in-ef-feature-ctp5-part-2-connections-and-models.aspx

In the "Other DbContext Designer Parameters" section:

...

  • You can pass the full connection string to the DbContext, and not just the database or connection string name. By default, this connection string is used with the Provider System.Data.SqlClient; this can be changed by setting a different implementation of IConnectionFactory to
    context.Database.DefaultConnectionFactory.
  • You can use an existing DbConnection object by passing it to the DbContext constructor. If the connection object is an instance of EntityConnection, then the model specified in the connection will be used in Database / Model First mode. If the object is an instance of another type - for example, SqlConnection - then the context will use it for Code First mode.

...

If this is true, you can use AES or other encryption to encrypt the string in the .config file, then decrypt at run time and pass it to the DbContext constructor.

+1
source

Source: https://habr.com/ru/post/1345578/


All Articles