Roger
Roger

Reputation: 269

How do I encrypt the connection string with EF 4.1 Code First?

I'm using the Code First RC to build a class library and I would like to be able to encrypt the connection string that I'm using. The consumers of the class library could be ASP.NET or Windows Forms apps, so I need an encryption method that works with both.

It appears that I can pass in a connection string to DbContext by name, but not by value, as shown here, so I don't think I can manually decrypt within my program before passing the string to DbContext. Could anyone point me in the right direction?

Upvotes: 4

Views: 3491

Answers (2)

Dave Swersky
Dave Swersky

Reputation: 34810

You can pass a full connection string into DbContext:

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

Under "Other DbContext Constructor Options":

...

  • You can pass a full connection string to DbContext instead of just the database or connection string name. By default this connection string is used with the System.Data.SqlClient provider; this can be changed by setting a different implementation of
    IConnectionFactory onto
    context.Database.DefaultConnectionFactory.
  • You can use an existing DbConnection object by passing it to a 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 some other type—for example, SqlConnection—then the context will use it for Code First mode.

...

If this is true, then you can use AES or some other encryption to encrypt the string in the .config file, then decrypt at runtime and feed it into the DbContext constructor.

Upvotes: 1

marc_s
marc_s

Reputation: 754518

You can easily encrypt any .NET configuration section - not just in ASP.NET as many devs seem to think, but absolutely also in other apps.

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

With this approach, you could encrypt the <connectionStrings> section - and to make it easier still, you could externalize that section into a separate file, too.

So in your app.config for your Winforms app, you'd have:

<connectionStrings configSource="ConnectionStrings.config" />

and the same would be in your web.config for your web application, and the file referenced would contain just the <connectionStrings> and that could be encrypted. Load the appropriate connection string from your config, and pass it into your DbContext constructor, and you should be fine.

Upvotes: 3

Related Questions