Encrypt password field with Entity Framework Model First

Ovilia picture Ovilia · Jul 30, 2012 · Viewed 13.1k times · Source

I'm using Entity Framework Model First in my project with VS2010.

I'm wondering if there is a way to set the field password to be encrypted in .edmx window or Properties windows maybe. I don't want to change the generated .cs file since it will be covered each time I modify the model.

Answer

Ladislav Mrnka picture Ladislav Mrnka · Jul 30, 2012

EF doesn't have any built in support for encryption and it also doesn't have support for database encryption mechanism (unless you are using transparent encryption in SQL Server which will encrypt whole database).

As a workaround you can do centralized encryption and decryption in your application. Here is high level idea:

  • Use a string property for your encrypted data - this property will be represented as nvarchar column in target database
  • Override SaveChanges method in your ObjectContext or DbContext inherited partial class (or handle SavingChanges event for ObjectContext inherited class). In this method / handler search for all instances of your entity which are in Added or Modified state (use ObjectStateManager or DbChangeTracker), take the value from the property which should be encrypted, encrypt it and store encrypted value back to the property in Base64 format. In case of SaveChanges override call base.SaveChanges after you encrypted property for all instances.
  • Handle ObjectMaterialized even on ObjectContext inherited class (in DbContext you will have to use IObjectContextAdapter to get ObjectContext instance from your DbContext instance), take the encrypted value from the property, convert it from Base64 format to byte array, decrypt it and store it back to the property. This may lead to some other complications because changing the property value may result in modified state but you should be able to fix it as well.