Encrypt password field with Entity Framework Model First

ef-model-first entity-framework sql-server visual-studio-2010

Question

In my VS2010 project, I'm utilizing Entity Framework Model First.

If there is a method to set the field, please let me know.password to be encrypted in windows zzz-12 zzz or zzz-16 zzz, if possible. Since the generated.cs file will be overwritten each time I update the model, I don't want to alter it.

1
4
7/30/2012 7:34:59 AM

Accepted Answer

Neither database encryption mechanisms nor built-in support for encryption are available in EF (unless you are using transparent encryption in SQL Server which will encrypt whole database).

You may implement centralized encryption and decryption in your application as a workaround. Here is a general concept:

  • Use astring your encrypted data will have a property, which will be shown asnvarchar target database column
  • Override SaveChanges approach in yourObjectContext or DbContext inheriting a handle or partial classSavingChanges occasion forObjectContext inheritable class). Search for all instances of your entity that are in this method's handler.Added or Modified state (make)ObjectStateManager or DbChangeTracker ), take the value to be encrypted from the property, encrypt it, and then save the encrypted value in Base64 format back in the property. If there isSaveChanges replace callbase.SaveChanges after the encryption of all instances' property.
  • Handle ObjectMaterialized the evenObjectContext inherited class (you must use this in DbContext)IObjectContextAdapter to getObjectContext example from yourDbContext For example, take the encrypted value from the property, convert it to byte array format from Base64, decode it, and then save the result back in the property. Other issues might arise as a consequence of the property value being changed, but you should be able to resolve these as well.
5
7/30/2012 8:15:26 AM

Popular Answer

Making a partial class that includes a new property that handles encryption and decoding might be an easier solution. In your code, you would then make use of this new property rather than the table object's Password attribute.

Partial Public Class ObjectName
  Public Property PasswordValue As String
    Get
      Return Password.Decrypt()
    End Get
    Set(value As String)
      Password = value.Encrypt()
    End Set
  End Property
End Class

In this instance, I did it by creating extension methods on the string object. I performed the encryption and decryption using the code found in the following link:

Unlock and unlock a string



Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow